import django.db
from django.utils.deprecation import MiddlewareMixin

from Ansjer import config as api_settings
from Object.ResponseObject import ResponseObject
from Service import CloudLogs
from Service.MiscellService import MiscellService


class StatisticsUrlMiddleware(MiddlewareMixin):
    def _https_statistics_to_reverse(self, request):
        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)
                return 0

    def _https_statistics_to_close(self, request):
        addsCount = len(api_settings.ADDR_URL)
        if addsCount > 0:
            api_settings.ADDR_URL.pop(0)

    def process_request(self, 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):
        self._https_statistics_to_close(request)
        if request.path != '/favicon.ico':
            CloudLogs.batch_add_access_log(request=request, status_code=response.status_code)
            try:
                MiscellService.add_access_log(request=request, status_code=response.status_code)
            except Exception as e:
                print(repr(e))
            django.db.close_old_connections()
        return response
