from django.contrib import messages
from django.conf import settings
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.urls import reverse
# Define role-based access to view modules
ROLE_ACCESS = {
    'commandant'            : 'account.adminViews',
    'dq'                    : 'account.dqViews',
    'battalion'             : 'account.battalionViews',
    'company'               : 'account.companyViews',
    'member'                : 'account.memberViews',
    'csm'                   : 'account.csmViews',
    'company_commander'     : 'account.companyCommanderViews',
    'adjutant'              : 'account.adjutantViews',
    'co'                    : 'account.coViews',
}


class RoleBasedAccessMiddleware(MiddlewareMixin):
    def process_view(self, request, view_func, view_args, view_kwargs):
        # Bypass for leaveCertificate URL
        if request.path.startswith('/account/leaveCertificate'):
            print("1st")
            return None
        
        
        if request.path == reverse('login') or request.path == reverse('doLogin'):
            return None
        # Allow static and media requests
        if request.path.startswith(settings.STATIC_URL) or request.path.startswith(settings.MEDIA_URL):
            return None
        user = request.user
        if not user.is_authenticated:
            # Bypass for leaveCertificate URL
            if request.path.startswith('/account/leaveCertificate'):
                print("2nd")
                return None
            return redirect('login')

        # Allow access to 'views.py' (common views for all roles)
        if view_func.__module__ in ('account.views', 'django.views.static', 
                            'django.contrib.admin.sites', 'django.contrib.admin.options','django.contrib.auth.admin','django_browser_reload.views'):
            return None  # No restriction for common views
        # Check user's role by related models
        elif hasattr(user, 'member'):
            role = 'member'
        elif hasattr(user, 'company'):
            role = 'company'
        elif hasattr(user, 'csm'):
            role = 'csm'
        elif hasattr(user, 'company_commander'):
            role = 'company_commander'
        elif hasattr(user, 'battalion'):
            role = 'battalion'
        elif hasattr(user, 'adjutant'):
            role = 'adjutant'
        elif hasattr(user, 'co'):
            role = 'co'
        elif hasattr(user, 'dq'):
            role = 'dq'
        elif hasattr(user, 'commandant'):
            role = 'commandant'
        else:
            messages.error(request, 'User is not connected to Category')
            print(request.user.role)
                    # Bypass for leaveCertificate URL
            if request.path.startswith('/account/leaveCertificate'):
                print("3rd")
                return None
            return redirect('login')  # Redirect if user has no role

        # Get allowed module for the role
        allowed_view_module = ROLE_ACCESS.get(role)

        # Check if the view belongs to the allowed module
        view_module = view_func.__module__
        print(f"view_func {view_func.__name__}")
        print(f"User: {user}, Role: {role}, View Module: {view_module}, Allowed Module: {allowed_view_module}")
        if view_module != allowed_view_module:
            # Bypass for leaveCertificate URL
            if request.path.startswith('/account/leaveCertificate'):
                print("4th")
                return None
            return redirect('login')

        return None  # Allow access if conditions pass
