"""Base Service class"""

import base64
import json
import os

from cachecontrol import CacheControl
import requests

from .. import __version__
from mapbox import errors


def Session(access_token=None, env=os.environ):
    """Returns an HTTP session.

    :param access_token: Mapbox access token string (optional).
    :param env: a dict.
    """
    access_token = (
        access_token or
        env.get('MapboxAccessToken') or
        env.get('MAPBOX_ACCESS_TOKEN'))
    session = requests.Session()
    session.params.update(access_token=access_token)
    session.headers.update({
        'User-Agent': 'mapbox-sdk-py/{0} {1}'.format(
            __version__, requests.utils.default_user_agent())})
    return session


class Service(object):
    """Service base class."""

    def __init__(self, access_token=None, cache=None):
        """Constructs a Service object.

        :param access_token: Mapbox access token string.
        :param cache: CacheControl cache instance (Dict or FileCache).
        """
        self.session = Session(access_token)
        if cache:
            self.session = CacheControl(self.session, cache=cache)

    @property
    def username(self):
        """Get username from access token.

        Token contains base64 encoded json object with username.
        """
        token = self.session.params.get('access_token')
        if not token:
            raise errors.TokenError(
                "session does not have a valid access_token param")
        data = token.split('.')[1]
        # replace url chars and add padding
        # (https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770)
        data = data.replace('-', '+').replace('_', '/') + "==="
        try:
            return json.loads(base64.b64decode(data).decode('utf-8'))['u']
        except (ValueError, KeyError):
            raise errors.TokenError(
                "access_token does not contain username")

    def handle_http_error(self, response, custom_messages=None,
                          raise_for_status=False):
        if not custom_messages:
            custom_messages = {}
        if response.status_code in custom_messages.keys():
            raise errors.HTTPError(custom_messages[response.status_code])
        if raise_for_status:
            response.raise_for_status()

@@ -1,16 +1,24 @@
 %22%22%22Base 
+Routing 
 Service 
@@ -125,17 +125,16 @@
 %0A%0Afrom .
-.
  import 
@@ -149,34 +149,8 @@
 n__%0A
-from mapbox import errors%0A
 %0A%0Ade
@@ -160,27 +160,22 @@
 ession(a
-ccess_token
+pi_key
 =None, e
@@ -231,35 +231,30 @@
     :param a
-ccess_token
+pi_key
 : Mapbox acc
@@ -319,27 +319,22 @@
 %22%22%0A    a
-ccess_token
+pi_key
  = (%0A   
@@ -339,27 +339,22 @@
        a
-ccess_token
+pi_key
  or%0A    
@@ -493,32 +493,22 @@
 te(a
-ccess_token=access_token
+pi_key=api_key
 )%0A  
@@ -679,16 +679,23 @@
 %0A%0Aclass 
+Routing
 Service(
@@ -710,17 +710,25 @@
 %0A    %22%22%22
-S
+Routing s
 ervice b
@@ -766,27 +766,22 @@
 (self, a
-ccess_token
+pi_key
 =None, c
@@ -849,27 +849,22 @@
 :param a
-ccess_token
+pi_key
 : Mapbox
@@ -1000,27 +1000,22 @@
 ession(a
-ccess_token
+pi_key
 )%0A      
@@ -1295,27 +1295,22 @@
 s.get('a
-ccess_token
+pi_key
 ')%0A     
@@ -1411,27 +1411,22 @@
  valid a
-ccess_token
+pi_key
  param%22)

modify it from mapbox-sdk-py's base class to rap's, not yet finished