import base64
import hashlib
import hmac
import json
import random
import time

from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import \
    TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.vod.v20180717 import models, vod_client

SecretId = 'AKIDa8RTEiwsYw4uTlpc8NL2SbS2MO9droUu'
SecretKey = 'A3f04oHTO1NSGn20Xpqa2D8l8D2aqpXy'

# 初始化点播client
def initClient():
    cred = credential.Credential(SecretId, SecretKey) 
    httpProfile = HttpProfile()
    httpProfile.endpoint = "vod.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = vod_client.VodClient(cred, "", clientProfile) 
    return client

def doResponse(res):
    # 处理返回结果
    # 转变为常用返回Response
    if hasattr(res, 'Error'):
        return Response(res._serialize(allow_none=True), status=HTTP_400_BAD_REQUEST)
    return Response(res._serialize(allow_none=True))

def getAllClass(params={}):
    # 获取所有分类
    try: 
        client = initClient()
        req = models.DescribeAllClassRequest()
        req.from_json_string(json.dumps(params))
        resp = client.DescribeAllClass(req) 
        return doResponse(resp)
    except TencentCloudSDKException as err: 
        print(err) 

def searchMedia(params={}):
    try: 
        client = initClient()
        req = models.SearchMediaRequest()
        req.from_json_string(json.dumps(params))
        resp = client.SearchMedia(req) 
        return doResponse(resp)
    except TencentCloudSDKException as err: 
        print(err)

def getSignature(procedure=None):
    """
    获取上传签名
    可指定
    """
    TimeStamp = int(time.time())
    ExpireTime = TimeStamp + 86400 * 365 * 10
    Random = random.randint(0, 999999)
    Original = "secretId=" + SecretId + "&currentTimeStamp=" + str(TimeStamp) + "&expireTime=" + str(ExpireTime) + "&random=" + str(Random)
    if procedure:
        Original = Original + "&procedure="+procedure
    Hmac = hmac.new(bytes(SecretKey, 'utf-8'), bytes(Original, 'utf-8'), hashlib.sha1)
    Sha1 = Hmac.digest()
    Signature = bytes(Sha1) + bytes(Original, 'utf-8')
    Signature2 = base64.b64encode(Signature)
    return str(Signature2, 'UTF-8')
