import json

from common.third_party_api.surveillance.base import BaseConfiguration

import requests

from common.utils.exceptions import ApiException

from common.third_party_api.surveillance.base import checkAuthentication, ApiAuthenticationError


class YSConfiguration(BaseConfiguration):
    def __init__(self, instance):
        self.instance = instance
        self.app_key = instance.app_key
        self.app_secret = instance.app_secret
        self.access_token = instance.access_token
        self.home_url = instance.home_url
        self.headers = {
            "Host": "open.ys7.com",
            "Content - Type": "application / x - www - form - urlencoded"
        }

    def set_access_token(self):
        url = "{}/api/lapp/token/get".format(self.home_url.rstrip("\\"))

        ret = requests.post(url=url,
                            headers=self.headers,
                            data={
                                "appKey": self.app_key,
                                "appSecret": self.app_secret
                            }).text
        ret = json.loads(ret)
        if ret.get("code") != "200":
            raise ApiException(msg_show="调用萤石云api失败, 请检查配置")
        self.instance.access_token = ret.get("data").get("accessToken")
        self.access_token = ret.get("data").get("accessToken")
        self.instance.save()
        return ret.get("data")

    def request(self, *args, **kwargs):
        url = "{}/api/lapp/{}".format(self.home_url.rstrip("/"),
                                      kwargs.get("url"))

        ret = requests.post(url=url, data=kwargs, headers=self.headers).text
        ret = json.loads(ret)
        return ret


class YSCloudClient(YSConfiguration):
    def create_device(self, **kwargs):

        param = {
            "accessToken": self.access_token,
            "deviceSerial": kwargs.get("deviceSerial"),
            "validateCode": kwargs.get("validateCode"),
            "url": "device/add"
        }
        ret = self.request(**param)
        if ret.get("code") == "10002":
            self.set_access_token()
            self.create_device(**kwargs)
        if ret.get("msg") == "accessToken不能为空":
            self.set_access_token()
            self.create_device(**kwargs)
        if ret.get("code") != "200":
            raise ApiException(msg_show="萤石云创建设备失败")
        return ret

    @checkAuthentication
    def get_video_url(self, **kwargs):
        url_list = []
        params = {
            "accessToken": self.access_token,
            "deviceSerial": kwargs.get("deviceSerial"),
            "channelNo": kwargs.get("channelNo", 1),
            "code": kwargs.get("code"),
            "protocol": kwargs.get("protocol"),
            "quality": kwargs.get("quality"),
            "startTime": kwargs.get("startTime"),
            "stopTime": kwargs.get("stopTime"),
            "type": kwargs.get("type"),
            "url": "v2/live/address/get"
        }
        ret = self.request(**params)
        if ret.get("code") in ["401", "10002"]:
            raise ApiAuthenticationError
        if ret.get("code") != "200":
            raise ApiException(msg_show="萤石云获取视频地址失败")
        url_list.append({
            "token": self.access_token,
            "url": ret.get("data").get("url") if ret.get("data") else None
        })
        return url_list

    def get_device_list(self, **kwargs):
        params = {
            "accessToken": self.access_token,
            "pageStart": kwargs.get("pageStart"),
            "pageSize": kwargs.get("pageSize",50),
            "url": "device/list"
        }
        res = self.request(**params)
        if res.get("code") == "10002":
            self.set_access_token()
            self.get_device_list(**kwargs)
        if res.get("code") != "200":
            raise ApiException(msg_show="萤石云设备列表获取失败")
        return res
