#!/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: 2019/12/23 10:30
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: PushDeploy.py
@Contact: pzb3076@163.com
"""
import os
import json
import math

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

from Model.models import pushDeployModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
import time
from Ansjer.config import BASE_DIR

class PushDeployView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(PushDeployView, self).dispatch(*args, **kwargs)

    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 operation is None:
            return response.json(444, 'error path')
        token = request_dict.get('token', None)
        # 设备主键uid
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if operation == 'adminAdd':
            return self.do_add(request_dict, response,userID,request)
        elif operation == 'adminDelete':
            return self.do_delete(request_dict, response,userID)
        elif operation == 'adminUpdate':
            return self.do_update(request_dict, response,userID, request)
        elif operation == 'adminQuery':
            return self.do_query(request_dict,response, userID)
        else:
            return response.json(414)

    def do_add(self, request_dict, response, userID, request):
        own_perm = ModelService.check_perm(userID, 40)
        if not own_perm:
            return response.json(404)
        name = request_dict.get('name', None)
        key = request_dict.get('key', None)
        secret = request_dict.get('secret', None)
        type = request_dict.get('type', None)
        nowTime = int(time.time())
        f = request.FILES.get('file', None)
        rv_path=''
        if f is not None:
            rv_path = 'static/pem/' + f.name
            path = os.path.join(BASE_DIR, rv_path)
            try:
                if os.path.exists(path):
                    os.remove(path)
                with open(path, 'wb+') as destination:
                    for chunk in f.chunks():
                        destination.write(chunk)
            except Exception as e:
                print('error:' + repr(e))
                return response.json(700, {'details': repr(e)})
        try:
            pushDeployModel.objects.create(addTime=nowTime, updTime=nowTime, name=name, key=key, secret=secret, pem=rv_path,
                                           type=type)
        except Exception as e:
            return response.json(10, repr(e))
        res = list(pushDeployModel.objects.values())
        return response.json(0, res)

    def do_query(self,request_dict, response,userID):
        own_perm = ModelService.check_perm(userID, 20)
        if own_perm is True:
            page = request_dict.get('page', None)
            line = request_dict.get('line', None)
            page = int(page)
            line = int(line)
            deviceContent = request_dict.get('content', None)
            if deviceContent:
                try:
                    searchCondition = json.loads(deviceContent)
                except Exception as e:
                    return response.json(10, repr(e))
                else:
                    kwargs = CommonService.get_kwargs(data=searchCondition)
                    uid_user_qs = pushDeployModel.objects.filter(**kwargs).order_by('-id')
                    if not uid_user_qs.exists():
                        return response.json(0, [])
                    count = uid_user_qs.count()
                    uid_user_ql = uid_user_qs[(page - 1) * line:page * line]. \
                        values('id', 'name', 'key', 'secret', 'pem', 'type',
                               'addTime', 'updTime')
                    uid_user_ls = CommonService.qs_to_list(uid_user_ql)
                    return response.json(0, {'datas': uid_user_ls, 'count': count})
            else:
                uid_user_qs = pushDeployModel.objects.all().order_by('-id')
                if not uid_user_qs.exists():
                    return response.json(0, [])
                count = uid_user_qs.count()
                uid_user_ql = uid_user_qs[(page - 1) * line:page * line]. \
                    values('id', 'name', 'key', 'secret', 'pem', 'type',
                           'addTime', 'updTime')
                uid_user_ls = CommonService.qs_to_list(uid_user_ql)
                return response.json(0, {'datas': uid_user_ls, 'count': count})
        else:
            return response.json(404)

    def do_update(self, request_dict, response,userID,request):
        own_perm = ModelService.check_perm(userID, 30)
        if not own_perm:
            return response.json(404)
        nowTime = int(time.time())
        id = request_dict.get('id', None)
        name = request_dict.get('name', None)
        key = request_dict.get('key', None)
        secret = request_dict.get('secret', None)
        type = request_dict.get('type', None)
        f = request.FILES.get('file', None)
        if f is not None:
            rv_path = 'static/pem/' + f.name
            path = os.path.join(BASE_DIR, rv_path)
            try:
                if os.path.exists(path):
                    os.remove(path)
                with open(path, 'wb+') as destination:
                    for chunk in f.chunks():
                        destination.write(chunk)
            except Exception as e:
                print('error:' + repr(e))
                return response.json(700, {'details': repr(e)})
            try:
                pushDeployModel.objects.filter(id=id).update(updTime=nowTime, name=name, key=key, secret=secret,
                                                             pem=rv_path,
                                                             type=type)
            except Exception as e:
                return response.json(10, repr(e))
        else:
            try:
                pushDeployModel.objects.filter(id=id).update(updTime=nowTime, name=name, key=key, secret=secret,
                                                             type=type)
            except Exception as e:
                return response.json(10, repr(e))

        # res = list(pushDeployModel.objects.values())
        return response.json(0, {'updTime': nowTime})

    def do_delete(self,request_dict, response, userID):
        own_perm = ModelService.check_perm(userID, 10)
        if not own_perm:
            return response.json(404)
        id = request_dict.get('id', None)
        try:
            pushDeployModel.objects.filter(id=id).delete()
        except Exception as e:
            return response.json(10, repr(e))
        res = list(pushDeployModel.objects.values())
        return response.json(0, res)

