#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2021/07/06 11:17
@Version: python3.6
@MODIFY DECORD:ansjer dev
"""
import json
import time
import urllib
import uuid
import boto3
import threading
import logging
from boto3.session import Session
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from django.views.generic.base import View
from Model.models import Device_Info, DeviceLogModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.UidTokenObject import UidTokenObject
from Service.CommonService import CommonService
from django.db.models import Q, F
from time import strftime


class DeviceDebug(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, request, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        response = ResponseObject()
        if not operation:
            return response.json(444,'operation')
        uidToken = request_dict.get('uidToken', None)
        if uidToken is not None:
            utko = UidTokenObject(uidToken)
            if utko.flag is False:
                return response.json(444, 'uidToken')
            uid = utko.UID
            if uid is not None:
                if operation == 'singleDebug':
                    return self.single_debug(request, request_dict, uid, response)
            return response.json(444, 'operation')
        else:
            if operation == 'deviceException':
                return self.device_exception(request, request_dict, response)
            return response.json(309)

    def single_debug(self,request, request_dict, uid, response):
        ip = CommonService.get_ip_address(request)
        device_info = logging.getLogger('device_info')
        device_info.info("----------------------------------------------------------------------------------")
        device_info.info("----------------------------------------------------------------------------------")
        device_info.info("----------------------------------------------------------------------------------")
        device_info.info("----------------------------------------------------------------------------------")
        device_info.info("----------------------------------------------------------------------------------")
        device_info.info("----------------------------------------------------------------------------------")
        device_info.info("debug----------------------------------------------------------------------------------start")
        device_info.info("uid："+uid)
        device_info.info(strftime("%Y-%m-%d %H:%M:%S"))
        device_info.info("ip："+ip)
        device_info.info(request_dict.get('debug_log'))
        device_info.info("debug------------------------------------------------------------------------------------end")
        return response.json(0,'debug success')
                # return response.json(10, '生成失败')

    #c1 pro设备上传异常日志
    def device_exception(self,request, request_dict, response):
        uid = request_dict.get('uid', None)
        serial_number = request_dict.get('serial_number', None)
        error_info = request_dict.get('error_info', None)

        # uid,serial_number二传一
        if not (uid or serial_number):
            return response.json(444)

        try:
            data_dict = {
                'error_info': error_info,
                'status': 3,
                'ip': CommonService.get_ip_address(request),
            }
            if uid:
                data_dict['uid'] = CommonService.decode_data(uid)
            else:
                data_dict['serial_number'] = CommonService.decode_data(serial_number)
            DeviceLogModel.objects.create(**data_dict)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
