from osinacore.models import *
from .serializers import *
from rest_framework.decorators import api_view
from .utils import *
import calendar
from django.contrib.auth.hashers import check_password
from datetime import datetime
import datetime as datetime2


@api_view(['POST'])
def login_user(request):
    try:
        username = request.data.get('username')
        password = request.data.get('password')
        if(not password or not username):
            raise ValueError("Missing fields")
        user = User.objects.get(username=username)
        serial = LoginSerializer(user)
        passwordValid = check_password(password, serial.data['password'])
        if passwordValid and StaffProfile.objects.filter(user=user):
                future = datetime.utcnow() + datetime2.timedelta(days=183)
                futuretime = calendar.timegm(future.timetuple())
                encoded_jwt = jwt.encode({"username": username, "exp": futuretime, "is_superuser": serial.data['is_superuser'], "userid":serial.instance.id}, "ibiye4700", algorithm="HS256")
                encoded_jwt = encoded_jwt.decode('utf-8')
                return successRes(msg={"token": encoded_jwt,"first_name":user.first_name,"last_name":user.last_name,"email":user.email, "id":user.id})
        else:
            raise ValueError("Incorrect password!")
    except User.DoesNotExist:
        return errorRes(msg="User doesn't exist!")
    except ValueError as err:
        return errorRes(msg=str(err))
    except Exception as e:
        print(e)
        return errorRes(default=True)
