from django import template

register = template.Library()

# Mapping from simplified permission names to actual module codes in RolePermission
# This must match the mapping in simplified_permissions_views.py
MODULE_NAME_TO_CODE = {
    'Dashboard': 'dashboard',
    'Clients': 'clients',
    'Loans': 'loans',
    'Repayments': 'repayments',
    'Portfolio': 'portfolio',
    'Reports & Statements': 'reports_statements',
    'Documents': 'documents',
    'Customer Documents': 'customer_documents',
    'Payment Receipts': 'payment_receipts',
    'Notifications': 'notifications',
    'Settings': 'settings',
    'Branch Settings': 'branch_settings',
    'System Settings': 'system_settings',
}

@register.filter
def format_module_name(value):
    """Format module name for display"""
    return value.replace('_', ' ').title()

@register.filter
def module_to_code(value):
    """Convert module name to code format - matches get_module_code() in simplified_permissions_views.py"""
    # Use the same mapping as the view
    return MODULE_NAME_TO_CODE.get(value, value.lower().replace(' ', '_').replace('&', '').replace('-', '_'))

@register.filter
def get_item(dictionary, key):
    """Get item from dictionary"""
    return dictionary.get(key)

@register.filter
def has_module_access(user, module):
    """Check if user has access permission for a specific module"""
    if not user or not user.is_authenticated:
        return False
    
    # Admin users have access to everything
    if user.is_superuser or user.role == 'admin':
        return True
    
    # Check if user has access permission for the module
    return user.has_permission(module, 'access')

@register.filter
def category_icon(category):
    """Get FontAwesome icon for permission category"""
    icon_map = {
        'dashboard': 'tachometer-alt',
        'loans': 'money-bill-wave',
        'payments': 'credit-card',
        'reports': 'chart-bar',
        'users': 'users',
        'settings': 'cog',
        'audit': 'shield-alt',
        'portfolio': 'briefcase',
        'analytics': 'chart-line',
        'notifications': 'bell',
        'security': 'lock',
        'system': 'server',
        'client': 'user-tie',
        'financial': 'dollar-sign',
        'management': 'tasks',
        'communication': 'comments',
        'export': 'download',
        'import': 'upload',
        'backup': 'database',
        'monitoring': 'eye',
        'compliance': 'clipboard-check',
    }
    return icon_map.get(category.lower(), 'circle')