# -*- coding: utf-8 -*-
#
import requests

errors = {-1: 'unexpected error',
           1: 'validation error',
           2: 'email_address not specified',
           3: 'password not specified',
           4: 'invalid email address password combination',
           5: 'both zip code and lat lon specified',
           6: 'lat specified without lon',
           7: 'lon specified without lat',
           8: 'zip code must be 5 digits long',
           9: 'invalid lat value',
           10: 'invalid lon value',
           11: 'invalid radius value',
           12: 'unknown user_id',
           13: 'unknown user_id_proxy',
           14: 'both user_id and user_id_proxy specified',
           15: 'neither user_id nor user_id_proxy specified',
           16: 'unknown tracking id',
           17: 'permission denied, not owner of tracking id',
           18: 'unknown namespace',
           19: 'duplicate tracking id',
           20: 'namespace not specified',
           21: 'value not specified',
           22: 'id not specified',
           23: 'unknown coupon id',
           24: 'coupon id not specified',
           25: 'coupon expired',
           26: 'coupon activation cap reached',
           27: 'coupon already activated by user',
           28: 'user must have at least one tracking id registered to activate coupon',
           29: 'retailer id not specified',
           30: 'unknown retailer id',
           31: 'coupon activated on the same card in another service',
           32: 'user_id_proxy not specified',
           33: 'duplicate user_id_proxy',
           34: 'email address is already associated with an account',
           37: 'the eCoupon could not be activated because it is not available at: Store 1, Store 2, ...',
           38: 'user_id not specified',
           50: 'payout_type not specified',
           51: 'invalid payout type',
           52: 'amount not specified',
           53: 'invalid amount',
           54: 'insufficient funds',
           55: 'paypal_email_address not specified',
           56: 'invalid paypal_email_address',
           57: 'bank_account_type not specified',
           58: 'invalid bank_account_type',
           59: 'bank_routing_number not specified',
           60: 'invalid bank_routing_number',
           61: 'bank_account_number not specified',
           62: 'invalid bank_account_number',
           63: 'email address not confirmed',
           64: 'tracking id already registered in another account',
           70: 'invalid product',
           80: 'fb_uid not specified',
           81: 'Unable to save the Facebook UID'
           }

class SavingStarAPI(object):

    def __init__(self, access_token=None, client_id=None, client_secret=None):
        self.access_token = access_token
        self.client_id = client_id
        self.client_secret = client_secret

        # OAuth
        #
        if self.access_token is None:
            x = self._getOAuthToken()
            if 'access_token' in x.keys():
                self.access_token = x['access_token']

    def getAccessToken(self):
        return self.access_token
        
    def _getOAuthToken(self):
        url = "https://api.savingstar.com/oauth/access_token"
        payload = {'client_id': self.client_id,
                   'client_secret': self.client_secret,
                   'grant_type': 'none'
                   }
        return self._doPost(url, payload)

    def _doGet(self, url):
        headers = {"Authorization": "OAuth " + self.access_token,
                   "Accept": "application/vnd.savingstar; version=2"
                   }
        resp = requests.get(url, headers=headers)
        if resp.status_code == 200:
            return resp.json()
        else:
            try:
                return resp.json()
            except ValueError:
                return {'error': {'code': resp.status_code,
                                  'message': resp.text
                                  }
                                  }

    def _doPost(self, url, payload):
        if self.access_token is not None:
            headers = {"Authorization": "OAuth " + self.access_token,
                       "Accept": "application/vnd.savingstar; version=2",
                       "Content-Type": "application/x-www-form-urlencoded"
                       }
            resp = requests.post(url, headers=headers, data=payload)
        else:
            resp = requests.post(url, data=payload)
        if resp.status_code == 200:
            return resp.json()
        else:
            try:
                return resp.json()
            except ValueError:
                return {'error': {'code': resp.status_code,
                                  'message': resp.text