import json
import datetime
from django.http import HttpResponse, JsonResponse
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin


def set_cookie(response, key, value, days_expire=7):
    if days_expire is None:
        max_age = 365 * 24 * 60 * 60  # one year
    else:
        max_age = days_expire * 24 * 60 * 60
    expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
    response.set_cookie(
        key,
        value,
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE or None,
    )

    return response

class ResponseInterceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        try:
            if type(response) == JsonResponse:
                for_save_to_session = request.user.user_profile.pop_node_by_name('for_save_to_session')
                if for_save_to_session:
                    data = json.loads(response.content)
                    data.update(for_save_to_session)
                    response.content = json.dumps(data)
        except Exception as e:
            msg = f'ResponseInterceptionMiddleware error = {str(e)}'
            print(msg)
        # if 'errors' in response.data:
        #     response.data.update({'success': False})
        # print(response.data)
        return response

    # def process_view(self, request, view_func, *view_args, **view_kwargs):
    #
    #     request.META.update({'ws_port': settings.WS_PORT})
    #
    #     # if request.user.is_authenticated and request.body:
    #     #     for_save_to_session = request.user.user_profile.pop_node_by_name('for_save_to_session')
    #     #     if for_save_to_session:
    #     #         data = json.loads(request.body)
    #     #         data.update(for_save_to_session)
    #     #
    #     # # request_data = getattr(request, '_body', request.body)
    #     # # request_data = json.loads(request_data)
    #     # # # here you can write the logic to append the payload to request data
    #     #         request._body = json.dumps(data)
    #     return None

    # def __call__(self, request):
    #     # Code to be executed for each request before
    #     # the view (and later middleware) are called.
    #
    #     if request.user.is_authenticated and request.body:
    #         for_save_to_session = request.user.user_profile.pop_node_by_name('for_save_to_session')
    #         if for_save_to_session:
    #             data = json.loads(request.body)
    #             data.update(for_save_to_session)
    #             request._body = json.dumps(data)
    #             # return JsonResponse(data)
    #         # request = request.user.user_profile.save_user_alerts_to_session(request)
    #
    #     response = self.get_response(request)
    #     # if request.user.is_authenticated:
    #     #     for_save_to_session = request.user.user_profile.pop_node_by_name('for_save_to_session')
    #     #     if for_save_to_session:
    #     #         for key, val in for_save_to_session.items():
    #     #             set_cookie(response, key, json.dumps(val), 30)
    #
    #     # Code to be executed for each request/response after
    #     # the view is called.
    #
    #     return response

