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

from django.conf import settings
from django.utils.http import cookie_date
from django.contrib.sessions.middleware import SessionMiddleware

from gm_logging.django.middleware import get_client_info_of_request

from engine.rpc_base import rpc_invoker


class HeliosController(object):

    __local = threading.local()

    @classmethod
    def enter_request(cls, request):
        # integrity with gm_logging
        client_info = get_client_info_of_request(request)

        rpc_invoker = cls.__get_base_rpc_invoker().with_config(
            session_key=request.session.session_key,
            client_info=client_info,
        )

        request.rpc = rpc_invoker
        cls.__local.request = request

    @classmethod
    def exit_request(cls, request):
        cls.__local.request = None

    @classmethod
    def get_current_rpc_invoker(cls):
        request = getattr(cls.__local, 'request', None)
        if request is None:
            # write log here
            return cls.__get_base_rpc_invoker()
        return request.rpc

    @classmethod
    def __get_base_rpc_invoker(cls):
        return settings.RPC_INVOKER

    @classmethod
    def get_current_request(cls):
        return getattr(cls.__local, 'request', None)


class HeliosMiddleware(object):

    def process_request(self, request):
        HeliosController.enter_request(request)

    def process_response(self, request, response):
        HeliosController.exit_request(request)
        return response
