from urllib.parse import urlencode

import requests
import ujson


class TelphinAPI(object):
    __access_cathedrals = None

    def __init__(self, app_id, secret, is_sandbox=False):
        """
        Constructor
        :param key: key from personal
        :param secret: secret from personal
        :param is_sandbox: (True|False)
        """
        self.app_id = app_id
        self.secret = secret
        self.is_sandbox = is_sandbox
        self.__url_api = 'https://apiproxy.telphin.ru'

    def _auth(self):
        data = dict(grant_type='client_credentials', client_id=self.app_id, client_secret=self.secret)
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        res = requests.post(f'{self.__url_api}/oauth/token', data=urlencode(data), headers=headers)
        if res.status_code != 200:
            raise Exception(f'Не удалось авторизоваться {res.content}')
        self.__access_cathedrals = res.json()

    def call(self, method, params=None, request_type='GET'):
        if not self.__access_cathedrals:
            self._auth()
        headers = {
            'Authorization': f'{self.__access_cathedrals["token_type"]} {self.__access_cathedrals["access_token"]}',
            'Content-Type': 'application/json'
        }
        url = f'{self.__url_api}'
        data = ujson.dumps(params)
        print(data)
        print(url+method)
        if request_type == 'GET':
            response = requests.get(url+method, headers=headers, data=data)
            return response
        elif request_type == 'POST':
            response = requests.post(url+method, headers=headers, data=data)
            return response
