import datetime
import json
import threading

from django.utils.timezone import utc

from Model.models import Access_Log
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.TemplateService import TemplateService


class MiscellService:

    @staticmethod
    def add_access_log(request, status_code):
        asy = threading.Thread(target=add_log_thread, args=(request, status_code))
        asy.start()


def add_log_thread(request, status_code):
    try:
        request.encoding = 'utf-8'
        if request.method == 'GET':
            request_dict = request.GET
        elif request.method == 'POST':
            request_dict = request.POST
        else:
            return
        api_list = TemplateService.log_api()
        request_path = request.path.strip().strip('/')
        if request_path in api_list:
            user = get_access_name(request_dict=request_dict)
            ip = CommonService.get_ip_address(request)
            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
            password = request_dict.get('userPwd', None)
            if password is not None:
                request_dict = dict(request_dict)
                request_dict.pop('userPwd')

            content = json.dumps(request_dict)

            add_data = {
                'user': user,
                'ip': ip,
                'status': status_code,
                'url': request.META['SERVER_PROTOCOL'] + '-' + request.method + '-' + request.path,
                'operation': request_path,
                'time': now_time,
                'content': content
            }
            Access_Log.objects.create(**add_data)
    except Exception as e:
        print(repr(e))
        pass


def get_access_name(request_dict):
    user_name = request_dict.get('userName', None)
    if user_name:
        return user_name
    email = request_dict.get('email', None)
    if email:
        return email
    phone = request_dict.get('phone', None)
    if phone:
        return phone
    token = request_dict.get('token', None)
    user = ''
    if token is not None:
        tko = TokenObject(token)
        if tko.code == 0:
            user = tko.user
    return user
