
import time
import logging
import json
import uuid
import random
import datetime

from django.conf import settings
from django.utils.http import cookie_date

from engine.logger import exception_logger, profile_logger
from engine.exception_info import get_exception_info, get_func_args


class TrackingMiddleware(object):
    """set/get tracking cookie."""

    def process_request(self, request):
        """check if tracking cookie exist"""
        if settings.TRACKING_COOKIE_NAME in request.COOKIES:
            request._has_tracking_cookie = True
            request.tracking_cookie = request.COOKIES[settings.TRACKING_COOKIE_NAME]

        else:
            request._has_tracking_cookie = False
            request.tracking_cookie = uuid.uuid1().hex + str(random.randrange(1, 10000))

    def process_response(self, request, response):
        if not request._has_tracking_cookie:
            expires_time = time.time() + settings.TRACKING_COOKIE_AGE
            expires = cookie_date(expires_time)
            response.set_cookie(
                settings.TRACKING_COOKIE_NAME,
                request.tracking_cookie,
                max_age=settings.TRACKING_COOKIE_AGE,
                expires=expires,
            )

        return response


class LoggingMiddleware(object):

    def process_request(self, request):
        request.start_time = time.time()

    def process_response(self, request, response):
        execute_time = time.time() - request.start_time
        path = request.get_full_path()
        gm_request_id = request.META.get('HTTP_X_GM_REQUEST_ID')

        try:
            items = {}
            if request.method == 'GET':
                items = request.GET.dict()

            elif request.method == 'POST':
                items = request.POST.dict()

            items = json.dumps(items)
        except:
            items = ''

        profile_logger.info(
            json.dumps(
                {
                    'timestamp': datetime.datetime.fromtimestamp(
                        request.start_time
                    ).strftime('%Y-%m-%dT%H:%M:%S+08:00'),
                    'request_method': request.method,
                    'path': path,
                    'execute_time': execute_time,
                    'items': items,
                    'gm_request_id': gm_request_id
                }
                , ensure_ascii=True
            )
        )
        return response

    def process_exception(self, request, exception):
        gm_request_id = request.META.get('HTTP_X_GM_REQUEST_ID')
        exc = get_exception_info()
        func_args = get_func_args()
        exception_logger.info(
            json.dumps(
                {
                    'gm_request_id': gm_request_id,
                    'stacktrace': exc,
                    'func_args': func_args,
                    'timestamp': datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+08:00'),
                }
                , ensure_ascii=True
            )
        )


class TrackingCityMiddleware(object):
    def process_request(self, request):
        current_city_id = request.GET.get('current_city_id', '')
        request.logger.app(tracking_id=request.tracking_cookie, current_city_id=current_city_id)

