import time
from functools import wraps

from authentication.models import Log, SystemUserProfile
import requests


def log_function_info(func):
    @wraps(func)
    def wrapper(request, *args, **kwargs):
        start_time = time.time()
        response = func(request, *args, **kwargs)
        duration = time.time() - start_time
        log = Log(
            user=request.user,
            function_name=func.__name__,
            request=request,
            response=response,
            request_body=request.data,
            response_body=response.data,
            duration=duration,
            status=response.status_code
        )
        log.save()
        return response

    return wrapper


def log_viewset_info(func):
    @wraps(func)
    def wrapper(viewset, request, *args, **kwargs):
        start_time = time.time()
        response = func(viewset, request, *args, **kwargs)
        duration = time.time() - start_time
        log = Log(
            user=request.user,
            function_name=func.__name__,
            request=request,
            response=response,
            request_body=request.data,
            response_body=response.data,
            duration=duration,
            status=response.status_code
        )
        log.save()
        return response

    return wrapper


def log_sms(func):
    @wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)
        operator = SystemUserProfile.objects.get(user=request.user)
        roles = None
        users = None
        message = request.data['message']
        if 'role' in request.data.keys():
            roles = request.data['role']
        if 'user' in request.data.keys():
            users = request.data['user']

        if roles != None and users != None:
            users = SystemUserProfile.objects.filter(role__name__in=roles, key__in=users,
                                                     province=operator.province).order_by('id')
        elif roles != None:
            users = SystemUserProfile.objects.filter(role__name__in=roles, province=operator.province).order_by('id')
        else:
            users = SystemUserProfile.objects.filter(key__in=users, province=operator.province).order_by('id')

        for user in users:
            u = "http://webservice.sahandsms.com/newsmswebservice.asmx/SendPostUrl?username=hamedan&password=ha123456&from=30002501&to={}&message={}".format(
                user.mobile, message)
            url = u.format()
            payload = {}
            headers = {"Content-Type": "application/x-www-form-urlencoded"}
            r = requests.request("GET", url, headers=headers, data=payload)
        return response

    return wrapper
