import os.path
import time
# from .models import Log
from tinydb import TinyDB, Query
from django.core import serializers
from datetime import datetime
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent.parent


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

        # Filter to log all request to url's that start with any of the strings below.
        # With example below:
        # /example/test/ will be logged.
        # /other/ will not be logged.
        self.prefixs = [
            '/example'
        ]

    def __call__(self, request):
        _t = time.time()  # Calculated execution time.
        response = self.get_response(request)  # Get response from view function.
        _t = int((time.time() - _t) * 1000)

        # If the url does not start with on of the prefixes above, then return response and dont save log.
        # (Remove these two lines below to log everything)
        # if not list(filter(request.get_full_path().startswith, self.prefixs)):
        #     return response

        # create data for log db
        db_data = {
            'endpoint': request.get_full_path(),
            'response_code': response.status_code,
            'method': request.method,
            'remote_address': self.get_client_ip(request),
            'exec_time': _t,
            # 'body_response': response.content.decode('utf-8'),
            'body_request': request.POST,
            'client_ip': self.get_client_ip(request),
            'browser_info': request.META['HTTP_USER_AGENT'],
            'log_created_at': str(datetime.now())
        }
        if request.user.is_authenticated:
            db_data.update({'user': serializers.serialize('json', [request.user, ])})
        # db = TinyDB(os.path.join(BASE_DIR, "logs/log.json"))
        # db.insert(db_data)
        return response

    # get clients ip address
    def get_client_ip(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            _ip = x_forwarded_for.split(',')[0]
        else:
            _ip = request.META.get('REMOTE_ADDR')
        return _ip
