# -*-coding:utf-8-*-
import requests
import io
import json
import string

class Api:
    host = "https://biz.apollo.starblingbling.com"
    mobile = "18512342222"
    pwd = "android"
    token = ""
    # def loadConfig(self):
    #     with io.open('config.json', "r+") as fin:
    #         return json.load(fin)


    # def updateConfig(self,config):
    #     with io.open("config.json", "w+") as fout:
    #         fout.write(json.dumps(config, ensure_ascii=False))


    def getToken(self):
        return self.token
        # with io.open('config.json', "r+") as fin:
        #     return json.load(fin)['token']


    # 登录
    def login(self,account, pwd):
        url = self.host+"/api/api/login"
        params = {'mobile': account, 'password': pwd}
        result = requests.post(url, params)
        if result.status_code == 200:
            self.token = result.json()['data']['token']
            # config = self.loadConfig()
            # config['token'] = token
            # self.updateConfig(config)
            # print("token已更新")
        else:
            print(result.json())

    def handleResult(self,result):
        if result.json()['code'] != "OK":
            print("api error: ",result.url)
            print(result.json())
            if "token invalid" in result.json()['message']:
                print("token失效，正在重新登录，稍后再试...")
                self.login(self.mobile,self.pwd)
        else:
            return True
        return False

    # 生成新的协议
    def new_privacy(self,crop_id, app_name, oss_path):
        self.login(self.mobile,self.pwd)
        url = self.host+"/api/api/privacies"
        params = {'corpId': crop_id, 'corpName': app_name, 'packageName': oss_path }
        header = {'X-AUTH-TOKEN':self.getToken()}
        result = requests.post(url, json=params,headers=header)

        if("corpId" in result.text and "packageName" in result.text and "exists" in result.text):
            print("文件已存在，正在转到更新接口...")
            success = self.update_privacy(crop_id,app_name,oss_path)
            if not success and result.json()['code'] != "OK":
                return False
        if self.upload_privacy(crop_id,oss_path):
            print("更新协议成功!")
            return True
        return False

    #更新协议
    def update_privacy(self,crop_id, app_name, oss_path):
        url = self.host+"/api/api/privacies/regenerate/%s/%s"%(crop_id,oss_path)
        params = {'corpId': crop_id, 'corpName': app_name, 'packageName': oss_path}
        header = {'X-AUTH-TOKEN':self.getToken()}
        result = requests.put(url, json=params,headers=header)
        return self.handleResult(result)
        
    #上传协议
    def upload_privacy(self,crop_id, oss_path):
        url = self.host+"/api/api/privacies/upload-to-oss/%s/%s"%(crop_id,oss_path)
        params = {'corpId': crop_id, 'packageName': oss_path}
        header = {'X-AUTH-TOKEN':self.getToken()}
        result = requests.put(url,json=params,headers=header)
        return self.handleResult(result)
