#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: Ansjer
@software: PyCharm
@DATE: 2018/6/15 16:47
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: DeviceLog.py
@Contact: chanjunkai@163.com
"""
import datetime

import simplejson as json
from django.views.decorators.csrf import csrf_exempt

from Model.models import Device_Info
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.mongodb import mongodb
from Service.CommonService import CommonService
from Service.DeviceOperation import DeviceOperation
from Service.ModelService import ModelService

'''
curl http://192.168.136.45:8077/devices/C2887N9EBS87ZAT1111A/logs -d "deviceData={\"UID\":\"C2887N9EBS87ZAT1111A\",\"type\":\"0x10014\",\"UserIP\":\"127.0.0.1\",\"time\":1529474865,\"name\":\"admin\"}"
http://192.168.136.40:8077/devices/2N1K3LE78TYJ38CE111A/logs?type=All&starttime=1529462169&endtime=1529462169
'''


@csrf_exempt
def DeviceLog(request, uid):
    # 存储设备日志
    response = ResponseObject()
    if request.method == 'POST':
        request.encoding = 'utf-8'
        deviceData = request.POST.get('deviceData', None)
        device_info = Device_Info.objects.filter(UID=uid)
        if device_info.exists():
            try:
                data = json.loads(deviceData)
                mdb = mongodb()
                data['et'] = datetime.datetime.utcnow()
                col = "log_device_operation"
                mdb.insert_one(col=col, data=data)
                return response.json(0)
            except Exception as e:
                print(repr(e))
                return response.json(48,repr(e))
        else:
            return response.json(173)
    # 查找设备日志
    if request.method == 'GET':
        request.encoding = 'utf-8'
        token = request.GET.get('token', None)
        page = request.GET.get('page', None)
        line = request.GET.get('line', None)
        type = request.GET.get('type', None)
        search_class = request.GET.get('class', None)
        starttime = request.GET.get('starttime', None)
        endtime = request.GET.get('endtime', None)
        if token is not None:
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code == 0:
                userID = tko.userID
                if page is None and line is None:
                    page = 1
                    line = 10000
                param_flag = CommonService.get_param_flag(data=[userID, page, line, uid])
                own_dev = ModelService.check_own_device(userID=userID, UID=uid)
                own_per = ModelService.check_perm(userID=userID, permID=30)
                if own_dev is True or own_per is True:
                    if param_flag is True:
                        query = {'uid': uid}
                        if search_class == 'All' or type == 'All':
                            pass
                        else:
                            try:
                                class_data= DeviceOperation.getODla(search_class=search_class)
                                query['type'] = {'$gte': class_data[0], '$lte': class_data[1]}
                            except Exception as e:
                                if type is not None:
                                    query['type'] = type
                        if starttime is not None and starttime != '' and endtime is not None and endtime != '':
                            query['time'] = {'$gte': int(starttime), '$lte': int(endtime)}
                        elif starttime is not None and starttime != '':
                            query['time'] = {'$gte': int(starttime)}
                        elif endtime is not None and endtime != '':
                            query['time'] = {'$lte': int(endtime)}
                        print('___________query____________')
                        print(query)
                        print('___________query____________')
                        mdb = mongodb()
                        col = "log_device_operation"
                        qs = mdb.findAll(col=col, page=int(page), line=int(line), query=query)
                        if qs is not False:
                            data_list = []
                            for i in qs['data']:
                                i['type'] = DeviceOperation.getOperation(type=i['type'])
                                data_list.append(i)
                            qs['data'] = data_list
                        return response.json(0,qs)
                else:
                    return response.json(404)
                return response.json(444)
            else:
                return response.json(tko.code)
        else:
            return response.json(309)