#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerPush
@software: PyCharm
@DATE: 2020/2/14 13:54
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: ShadowController.py
@Contact: chanjunkai@163.com
"""
# 测试环境
# test.shadow.dvema.com
# 生产环境
# shadow.dvema.com
# 设备影子更新
from Object.LogUtil import LogUtil
from Object.ResponseObject import ResponseObject
from Object.ETkObject import ETkObject
import time
from Model.models import Device_Info, UidSetModel, UID_Preview, VoicePromptModel, UID_Bucket
from Service.CommonService import CommonService
from django.http import JsonResponse
from Object.UidTokenObject import UidTokenObject

def generate_utk(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'GET':
        request_dict = request.GET
    elif request.method == 'POST':
        request_dict = request.POST
    else:
        return response.json(444,'wrong method')
    username = request_dict.get('username',None)
    password = request_dict.get('password',None)
    uid = request_dict.get('uid',None)
    if username and password:
        if username == 'debug_user' and password == 'debug_password':
            # utko = UidTokenObject()
            # # right
            # utko.generate(data={'uid': uid})
            etkObj = ETkObject(etk='')
            etk = etkObj.encrypt(uid)
            return response.json(0, {'etk': etk})
        else:
            return response.json(404)
    else:
        return response.json(444,'username password')


# 设备影子更新
def update_device_shadow(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(444)
    etk = request_dict.get('etk', None)
    eto = ETkObject(etk)
    uid = eto.uid
    if uid:
        # 重置按钮
        is_reset = request_dict.get('is_reset', None)
        # 传1则重置设备信息
        if is_reset == '1':
            UidSetModel.objects.filter(uid=uid).delete()
            # 重置设备，判断设备为已删除
            nowTime = int(time.time())
            uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=nowTime).values('id', 'has_unused').order_by('addTime')
            if not uid_bucket.exists():
                di_qs = Device_Info.objects.filter(UID=uid)
                di_qs.update(isExist=2)
            # 删除预览图
            uid_pre_qs = UID_Preview.objects.filter(uid=uid)
            if uid_pre_qs.exists():
                uid_pre_qs.delete()

            # 删除语音提示
            voice_qs = VoicePromptModel.objects.filter(uid=uid)
            if voice_qs.exists():
                voice_qs.delete()

        # return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
        ucode = request_dict.get('ucode', None)
        version = request_dict.get('version', None)
        p2p_region = request_dict.get('p2p_region', None)
        tz = request_dict.get('tz', None)
        video_code = request_dict.get('video_code', None)
        ip = CommonService.get_ip_address(request)
        channel = request_dict.get('channel', None)
        cloud_vod = request_dict.get('cloud_vod', None)
        push_status = request_dict.get('push_status', None)
        pwd = request_dict.get('pwd', None)
        resetTime = request_dict.get('resetTime', None)
        is_alexa = request_dict.get('is_alexa', None)
        is_human = request_dict.get('is_human', None)
        is_custom_voice = request_dict.get('is_custom', None)
        double_wifi = request_dict.get('double_wifi', None)

        us_qs = UidSetModel.objects.filter(uid=uid)
        # 更新
        nowTime = int(time.time())

        print('-------')
        print(resetTime)
        print('-------')
        qs_dict = {
            'updTime': nowTime,
            'ip': ip
        }
        if channel:
            qs_dict['channel'] = channel
        if p2p_region:
            qs_dict['p2p_region'] = p2p_region
        if ucode:
            qs_dict['ucode'] = ucode
        if version:
            qs_dict['version'] = version
        if tz:
            qs_dict['tz'] = tz
        if video_code:
            qs_dict['video_code'] = video_code
        if cloud_vod:
            qs_dict['cloud_vod'] = cloud_vod
        if push_status:
            qs_dict['detect_status'] = push_status
        if pwd:
            qs_dict['pwd'] = pwd
        if is_human:
            qs_dict['is_human'] = is_human
        if is_custom_voice:
            qs_dict['is_custom_voice'] = is_custom_voice
        if double_wifi:
            qs_dict['double_wifi'] = double_wifi
        if us_qs.exists():
            if is_alexa and us_qs[0].is_alexa == 0:
                qs_dict['is_alexa'] = is_alexa
            us_qs.update(**qs_dict)
            # 如果推送状态开启，返回推送url
            return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
        # 新增
        else:
            if is_alexa:
                qs_dict['is_alexa'] = is_alexa
            qs_dict['uid'] = uid
            qs_dict['addTime'] = nowTime
            UidSetModel.objects.create(**qs_dict)
            # 如果推送状态开启，返回推送url
            return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
    else:
        return JsonResponse(status=200, data={'code': 403, 'msg': 'error etk'})