#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import boto3
import botocore
from django.views.generic.base import View
from Model.models import DeviceLogModel
from Service.CommonService import CommonService
from Object.ResponseObject import ResponseObject
from Ansjer.config import REGION_NAME, ACCESS_KEY_ID, SECRET_ACCESS_KEY, LOG_BUCKET


class DeviceLogView(View):

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

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

    def validate(self, request, request_dict, operation):
        response = ResponseObject()
        token = request_dict.get('token', None)
        time_stamp = request_dict.get('time_stamp', None)
        # 时间戳token校验
        if not CommonService.check_time_stamp_token(token, time_stamp):
            return response.json(13)

        if operation == 'getUploadUrl':
            return self.getUploadUrl(request_dict, response)
        elif operation == 'uploaded':
            return self.uploaded(request, request_dict, response)
        else:
            return response.json(414)

    def getUploadUrl(self, request_dict, response):
        uid = request_dict.get('uid', None)
        serial_number = request_dict.get('serial_number', None)
        file_type = request_dict.get('file_type', None)
        file_num = int(request_dict.get('file_num', 1))

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

        try:
            device_id = uid if uid else serial_number
            device_id = CommonService.decode_data(device_id)
            put_url_list = []
            for num in range(file_num):
                # 日志文件名
                name = CommonService.createOrderID()
                filename = str(name) + '.' + file_type
                obj = 'device_log/{device_id}/'.format(device_id=device_id) + filename
                aws_s3_client = boto3.client(
                    's3',
                    region_name=REGION_NAME,
                    aws_access_key_id=ACCESS_KEY_ID,
                    aws_secret_access_key=SECRET_ACCESS_KEY,
                    config=botocore.client.Config(signature_version='s3v4'),
                )
                put_url = aws_s3_client.generate_presigned_url(
                    ClientMethod='put_object',
                    Params={
                        'Bucket': LOG_BUCKET,
                        'Key': obj
                    },
                    ExpiresIn=3600
                )
                put_url_dict = {'put_url': put_url, 'filename': filename}
                put_url_list.append(put_url_dict)
            return response.json(0, {'put_url_list': put_url_list})
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def uploaded(self, request, request_dict, response):
        uid = request_dict.get('uid', None)
        serial_number = request_dict.get('serial_number', None)
        status = request_dict.get('status', None)
        filename = request_dict.get('filename', None)

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

        try:
            data_dict = {
                'filename': filename,
                'status': int(status),
                '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, repr(e))
