#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

import oss2
from django.views import View

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
from Model.models import DeviceTypeModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


class DeviceTypeView(View):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        operation = kwargs.get('operation', None)
        return self.validate(request_dict, operation)

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

    def validate(self, request_dict, operation):
        token = request_dict.get('token', None)
        lang = request_dict.get('lang', None)

        response = ResponseObject(lang=lang)
        token = TokenObject(token)
        if token.code != 0:
            return response.json(token.code)

        if operation == 'add':
            return self.do_admin_add(token.userID, request_dict, response)
        elif operation == 'query':
            return self.do_query(request_dict, response)
        elif operation == 'delete':
            return self.do_admin_delete(token.userID, request_dict, response)
        elif operation == 'getUploadUrl':
            return self.get_upload_url(request_dict, response)
        else:
            return response.json(404)

    def get_upload_url(self, request_dict, response):
        upload_type = request_dict.get('upload_type', None)

        if upload_type:
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
            name = CommonService.createOrderID()
            filename = str(name) + '.' + upload_type
            obj = 'device_type/' + filename
            url = bucket.sign_url('PUT', obj, 7200)
            return response.json(0, {'put_url': url, 'filename': filename})
        else:
            return response.json(444)

    def do_admin_add(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 10)
        if not own_perm:
            return response.json(404)

        name = request_dict.get('name', None)
        model = request_dict.get('model', None)
        type = request_dict.get('type', None)
        ptz_type = request_dict.get('ptz_type', None)
        icon = request_dict.get('icon', None)

        if name and model and type and ptz_type and icon:
            now_time = int(time.time())
            device_type = DeviceTypeModel()
            device_type.name = name
            device_type.model = model
            device_type.type = type
            device_type.ptz_type = ptz_type
            device_type.icon = icon
            device_type.add_time = now_time
            device_type.update_time = now_time
            device_type.save()
            return response.json(0)
        else:
            return response.json(444)

    def do_query(self, request_dict, response):
        device_type_qs = DeviceTypeModel.objects.filter().values('id', 'type', 'ptz_type', 'model', 'icon', 'name')
        res = {}
        data = []
        res['data'] = data
        if device_type_qs.exists():
            for device_type in device_type_qs:
                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')

                icon = device_type['icon']
                url = 'device_type/' + icon
                device_type['icon'] = bucket.sign_url('GET', url, 3600)
                data.append(device_type)

        return response.json(0, res)

    def do_admin_delete(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 10)
        if not own_perm:
            return response.json(404)

        id = request_dict.get('id', None)
        if id:
            DeviceTypeModel.objects.filter(id=id).delete()
            return response.json(0)
        else:
            return response.json(444)
