from django import template
from django.utils.safestring import mark_safe
import json

register = template.Library()

@register.filter
def get_item(dictionary, key):
    """Get item from dictionary by key"""
    if isinstance(dictionary, dict):
        return dictionary.get(key, {})
    return {}

@register.filter
def get_module_icon(module):
    """Get FontAwesome icon for module"""
    icons = {
        'dashboard': 'tachometer-alt',
        'users': 'users',
        'clients': 'user-friends',
        'loans': 'money-bill-wave',
        'applications': 'file-contract',
        'repayments': 'hand-holding-usd',
        'reports': 'chart-bar',
        'documents': 'file-alt',
        'settings': 'cogs',
        'notifications': 'bell',
        'audit': 'clipboard-list',
        'kyc': 'id-card',
        'payments': 'credit-card',
        'communications': 'envelope',
        'portfolio': 'briefcase',
        'receipts': 'receipt',
        'statements': 'file-invoice',
        'media': 'images',
        'backup': 'database',
        'system': 'server'
    }
    return icons.get(module, 'cog')

@register.filter
def get_role_badge_class(role):
    """Get CSS class for role badge"""
    classes = {
        'admin': 'bg-red-100 text-red-800',
        'team_leader': 'bg-blue-100 text-blue-800',
        'loan_officer': 'bg-green-100 text-green-800',
        'secretary': 'bg-purple-100 text-purple-800',
        'borrower': 'bg-gray-100 text-gray-800',
    }
    return classes.get(role, 'bg-gray-100 text-gray-800')

@register.filter
def get_role_icon(role):
    """Get FontAwesome icon for role"""
    icons = {
        'admin': 'crown',
        'team_leader': 'user-tie',
        'loan_officer': 'handshake',
        'secretary': 'user-secret',
        'borrower': 'user',
    }
    return icons.get(role, 'user')

@register.filter
def permission_status_class(permission_info):
    """Get CSS class for permission status"""
    if not isinstance(permission_info, dict):
        return 'bg-gray-100 text-gray-800'
    
    source = permission_info.get('source', 'default')
    allowed = permission_info.get('allowed', False)
    
    if source == 'custom':
        return 'bg-yellow-100 text-yellow-800' if allowed else 'bg-orange-100 text-orange-800'
    elif source == 'role':
        return 'bg-blue-100 text-blue-800' if allowed else 'bg-red-100 text-red-800'
    else:
        return 'bg-gray-100 text-gray-800'

@register.filter
def permission_status_icon(permission_info):
    """Get FontAwesome icon for permission status"""
    if not isinstance(permission_info, dict):
        return 'ban'
    
    source = permission_info.get('source', 'default')
    allowed = permission_info.get('allowed', False)
    
    if source == 'custom':
        return 'user-cog'
    elif source == 'role':
        return 'users-cog'
    else:
        return 'ban'

@register.filter
def jsonify(value):
    """Convert Python object to JSON string"""
    return mark_safe(json.dumps(value))

@register.simple_tag
def permission_count(permissions, filter_type='all'):
    """Count permissions based on filter type"""
    if not isinstance(permissions, dict):
        return 0
    
    count = 0
    for module, actions in permissions.items():
        if isinstance(actions, dict):
            for action, perm_info in actions.items():
                if filter_type == 'all':
                    count += 1
                elif filter_type == 'allowed':
                    if isinstance(perm_info, dict) and perm_info.get('allowed', False):
                        count += 1
                    elif isinstance(perm_info, bool) and perm_info:
                        count += 1
                elif filter_type == 'custom':
                    if isinstance(perm_info, dict) and perm_info.get('source') == 'custom':
                        count += 1
    
    return count

@register.inclusion_tag('users/partials/permission_badge.html')
def permission_badge(permission_info, action_name):
    """Render permission badge"""
    return {
        'permission_info': permission_info,
        'action_name': action_name,
    }

@register.inclusion_tag('users/partials/role_badge.html')
def role_badge(role, size='sm'):
    """Render role badge"""
    return {
        'role': role,
        'size': size,
    }

@register.filter
def replace(value, args):
    """Replace string in value"""
    if not args or ',' not in args:
        return value
    
    old, new = args.split(',', 1)
    return value.replace(old, new)

@register.filter
def title_case(value):
    """Convert to title case and replace underscores"""
    if not value:
        return value
    return value.replace('_', ' ').title()

@register.filter
def has_custom_permissions(user):
    """Check if user has any custom permissions"""
    try:
        from users.models import UserPermission
        return UserPermission.objects.filter(user=user).exists()
    except:
        return False

@register.filter
def custom_permission_count(user):
    """Count custom permissions for user"""
    try:
        from users.models import UserPermission
        return UserPermission.objects.filter(user=user).count()
    except:
        return 0

@register.simple_tag
def has_permission(user, module, action):
    """Check if user has permission for module and action"""
    if not user or not user.is_authenticated:
        return False
    try:
        return user.has_permission(module, action)
    except:
        return False