#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.utils.deprecation import MiddlewareMixin

from Ansjer import local_settings as api_settings
from Ansjer.config import SERVER_TYPE

from Object.ResponseObject import ResponseObject
from Service.MiscellService import MiscellService
from Service import OperatingLogs
import django.db


# 设置mysql超时


class StatisticsUrlMiddleware(MiddlewareMixin):
    def _https_statistics_to_reverse(self, request):
        '''

        :param request:
        :return:
        '''
        # 限制同时下载量
        path = request.path
        index = path.find('/OTA/downloads')
        if index != -1:
            addsCount = len(api_settings.ADDR_URL)
            if addsCount > 1000:
                return -1
            else:
                adds = request.META.get('REMOTE_ADDR', None)
                api_settings.ADDR_URL.append(adds)
                # MiscellService.add_ota_download_log(request=request)
                return 0

    def _https_statistics_to_close(self, request):
        '''

        :param request:
        :return:
        '''
        addsCount = len(api_settings.ADDR_URL)
        if addsCount > 0:
            api_settings.ADDR_URL.pop(0)

    def process_request(self, request):
        '''
        :function description
            Request预处理函数: process_request(self, request)
        :param request:
        :return: 应当返回 None 或 HttpResponse 对象
             如果返回 None ，Django 将继续处理这个 request，执行后续的中间件，
        然后调用相应的 view。
             如果返回 HttpResponse 对象，Django 将不再执行任何其它的中间件
        (无视其种类)以及相应的view。 Django将立即返回该 HttpResponse。
        '''
        if request.path != '/favicon.ico':
            print('process_request', request)
        result = self._https_statistics_to_reverse(request)
        if result == -1:
            response = ResponseObject()
            return response.json(910)
        return None

    def process_view(self, request, callback, callback_args, callback_kwargs):
        if request.path != '/favicon.ico':
            print('process_view', request)
        return None

    def process_response(self, request, response):
        '''
        :function description
            Response后处理函数: process_response(self, request, response)
            这个方法的调用时机在 Django 执行 view 函数并生成 response 之后。
        :param request: request 对象
        :param response: 从 view 中返回的 response 对象
        :return: 必须返回 HttpResponse 对象. 这个 response 对象可以是传入函数的那一个原始对象（通常已被修改），也可以是全新生成的。
            该处理器能修改 response 的内容；一个常见的用途是内容压缩，如 gzip 所请求的 HTML 页面。
        '''
        self._https_statistics_to_close(request)
        ########记录访问日志
        # MiscellService.DynamoDB_add_access_log(request=request, status_code=response.status_code)
        if request.path !='/favicon.ico':
            print('process_response', request, response)
            try:
                pass
                # mysql
                if SERVER_TYPE!="Ansjer.formal_settings":
                    # print('添加日志')
                    OperatingLogs.add_access_log(request=request, status_code=response.status_code)
                    MiscellService.add_access_log(request=request, status_code=response.status_code)
                # else:
                #     print('不添加日志')
                # mongodb版
                # MiscellService.access_log(request=request, response=response, type=0)
            except Exception as e:
                print(repr(e))
            django.db.close_old_connections()
        return response