#!/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: 2020/8/14 10:13
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: AlexaConnectNum.py
@Contact: sonalh@foxmail.com
"""
from django.views.generic.base import View
import os

import json
import math
import time
import urllib
import logging
import logging
import requests
import time
import datetime
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from Model.models import AlexaConnectStatisticsModel
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View
from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.ModelService import ModelService
from django.db import connection

rtspServer = "rtsp.zositech.org,3.16.66.144"

# 获取alexa连接数接口
class AlexaConnectNum(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(AlexaConnectNum, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        response = ResponseObject()
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        #每隔十分钟定时保存每天最高连接数，crontab 在alexa_oauth2_oserver
        if operation == 'saveConnectNum':
            today = datetime.date.today()
            today_start_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d')))
            today_end_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d'))) + 86399
             #获取当前连接数
            current_connect_num = self.currentConnect()
            today_data = AlexaConnectStatisticsModel.objects.\
                filter(data_time__lte=today_end_time,data_time__gte=today_start_time).values('num','data_time')
            if today_data.exists():
                num = list(today_data)[0]['num']
                if current_connect_num > num:
                    today_data.update(num=current_connect_num, data_time=time.time())
            else:
                today_data.create(num=current_connect_num, data_time=time.time())
            return response.json(0)
        return response.json(10006)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        response = ResponseObject()
        operation = kwargs.get('operation')
        post_data = request.POST
        token = post_data.get('token', None)
        # tko = TokenObject()
        # newToken = tko.generate( data={'userID': '158943594633713800138000', 'lang': 'cn', 'user': '597471180@qq.com', 'm_code': '123413243214'})
        # return response.json(0, {'data': newToken})
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        own_permission = ModelService.check_perm(userID=userID, permID=30)
        if own_permission is not True:
            return response.json(404)

        #获取当前连接数
        current_connect_num = self.currentConnect()
        res = []
        #最近三十天每天最高连接数
        if operation == 'thirtyDays':
            query_num = AlexaConnectStatisticsModel.objects.\
                extra(select={"data_time": "FROM_UNIXTIME(data_time, '%%m-%%d')"}).\
                values('num', 'data_time').order_by('-data_time')[:30]
            res = list(query_num)

        #最近十二个月每月最高连接数
        if operation == 'years':
            cursor=connection.cursor()
            cursor.execute("SELECT FROM_UNIXTIME(data_time,'%Y-%m') as month, max(num) as max_num FROM alexa_statistics GROUP BY month order by month asc LIMIT 12")
            res_query = cursor.fetchall()
            for max_num, month in res_query:
                res.append({'num':month, 'month':max_num})

        res_desc = {'result_code': 0, 'reason': '成功', 'current_num':current_connect_num, 'top_num': res, 'error_code': 0}
        result_json = json.dumps(res_desc, ensure_ascii=False)
        return HttpResponse(result_json)

    def currentConnect(self):
        urls = rtspServer.split(',')
        httpPrefix = 'http://'
        postfix = ':10008/api/v1/pushers'
        current_connect_num = 0
        for url in urls:
            apiUrl = httpPrefix + url + postfix
            try:
                selectRtsp = requests.get(url=apiUrl, timeout=5)
                current_connect_num += selectRtsp.json()['total']
            except Exception as e:
                continue
        return current_connect_num












