from django.views import View
from django.contrib import messages
from django.shortcuts import render, redirect
from django.http import HttpResponseNotAllowed
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import authenticate, login, logout

from apps.accounts.models import Account

# Create your views here.

class LoginView(View): 
    
    # Handle GET request logic.
    def get(self, request, *args, **kwargs):
        # If user is already authenticated, redirect to the dashboard.
        if request.user.is_authenticated:
            return redirect("core:dashboard") 
        template = "authentication/login.html"
        context={}
        # Render the login form for GET requests. 
        return render(request, template, context)  
    
    # Handle POST request logic.    
    def post(self, request, *args, **kwargs):  
        # Extract username (email) and password from the POST data.
        email = request.POST.get("email")
        password = request.POST.get("password")  
        # Check if both email and password are provided.
        if email and password:
            # Fetch the user based on the provided email.
            user = Account.objects.filter(email=email).first() 
            # If a user with the provided email exists.
            if user:
                # Check if the user is not active and not a superuser.
                if not user.is_active and not user.is_superuser: 
                    # Redirect to the login page with the appropriate message. 
                    messages.error(request, "Your account is not active.")
                    return redirect("authentication:login") 
                # Check if the provided password is correct.
                if not user.check_password(password): 
                    # Redirect to the login page with the appropriate message.  
                    messages.error(request, "Invalid password.")
                    return redirect("authentication:login")  
                # Authenticate the user.
                user = authenticate(request, email=email, password=password)
                # If the user is authenticated.
                if user is not None:
                    # Login the user.
                    login(request, user) 
                    # Redirect to the dashboard or desired page.
                    return redirect("core:dashboard") 
                else: 
                    # Redirect to the login page with the appropriate message.  
                    messages.error(request, "Authentication failed.")
                    return redirect("authentication:login")  
            else: 
                # Redirect to the login page with the appropriate message.  
                messages.error(request, "User with this email does not exist.")
                return redirect("authentication:login")   
        else: 
            # Redirect to the login page with the appropriate message.  
            messages.error(request, "Please provide both email and password.")
            return redirect("authentication:login")   
        
    # Handle other HTTP methods using dispatch method
    def dispatch(self, request, *args, **kwargs):
        if request.method not in ["GET", "POST"]:
            return HttpResponseNotAllowed(["GET", "POST"])
        return super().dispatch(request, *args, **kwargs)

class LogoutView(LoginRequiredMixin, View):  
    
    # Handle GET request logic. 
    def get(self, request, *args, **kwargs):
        logout(request)
        self.request.session.flush()
        return redirect("authentication:login") 
    
    # Handle POST request logic. 
    def post(self, request, *args, **kwargs):
        logout(request)
        self.request.session.flush()
        return redirect("authentication:login") 
    
    # Handle other HTTP methods using dispatch method
    def dispatch(self, request, *args, **kwargs):
        if request.method not in ["GET", "POST"]:
            return HttpResponseNotAllowed(["GET", "POST"])
        return super().dispatch(request, *args, **kwargs)