import base64
import json

import requests
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA

from etc.settings.local import PUBBLIC_KEY, \
    ORGANIZATION_CODE, TOKEN_URL, UPLOAD_FILE_URL, GET_FILE_URL


class BaseClient(object):
    def __init__(self):
        """
        鉴权
        :return: 栾数的token
        """
        pub_key = PUBBLIC_KEY
        key = RSA.importKey(pub_key)
        pk = PKCS1_v1_5.new(key)
        organization_code = ORGANIZATION_CODE
        encrypt_text = pk.encrypt(organization_code.encode())
        code = base64.b64encode(encrypt_text)
        url = TOKEN_URL
        response = requests.post(url=url, data={"key": code})
        text = json.loads(response.text)
        self.token = text.get("token")

    def upload_file(self, file, file_id):
        header = {"Authorization": self.token}
        url = UPLOAD_FILE_URL
        response = requests.request("POST",
                                    url=url,
                                    data={
                                        "pk-id": file_id,
                                        "file-contents": file
                                    },
                                    headers=header)
        text = json.loads(response.text)
        return text.get("code")

    def get_file_url(self, file_id, type):
        url = GET_FILE_URL
        headers = {"Authorization": self.token}
        params = {"pkId": file_id, "type": type}
        response = requests.get(url, params=params, headers=headers)
        text = json.loads(response.text)
        return text
