import routeros_api
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User

# A dummy user is used to authenticate against Django's session management.
# This is not a real user in the database, but a temporary, in-memory user.
# This is required to use the @login_required decorator.
# We create the user if it does not exist.
try:
    User.objects.get(username='dummy')
except User.DoesNotExist:
    User.objects.create_user('dummy', password='dummy')

def login_view(request):
    if request.method == 'POST':
        router_ip = request.POST.get('router_ip')
        username = request.POST.get('username')
        password = request.POST.get('password')

        try:
            connection = routeros_api.RouterOsApiPool(
                router_ip,
                username=username,
                password=password,
                plaintext_login=True
            )
            api = connection.get_api()
            # If connection is successful, store credentials in session
            request.session['router_ip'] = router_ip
            request.session['username'] = username
            request.session['password'] = password
            
            user = User.objects.get(username='dummy')
            login(request, user)

            return redirect('dashboard')
        except Exception as e:
            # Handle connection error
            return render(request, 'core/login.html', {'error': str(e)})

    return render(request, 'core/login.html')

@login_required(login_url='/')
def dashboard_view(request):
    router_ip = request.session.get('router_ip')
    username = request.session.get('username')
    password = request.session.get('password')

    if not all([router_ip, username]):
        return redirect('login')

    try:
        connection = routeros_api.RouterOsApiPool(
            router_ip,
            username=username,
            password=password,
            plaintext_login=True
        )
        api = connection.get_api()

        # Fetch PPPoE secrets
        ppp_secrets = api.get_resource('/ppp/secret').get()

        # Fetch Hotspot users
        hotspot_users = api.get_resource('/ip/hotspot/user').get()

        # Process data
        customers = []
        for user in ppp_secrets:
            customers.append({
                'id': user.get('id'),
                'name': user.get('name'),
                'mac_address': user.get('caller-id', '-'),
                'type': 'PPPoE',
                'profile': user.get('profile', '-'),
                'expires': user.get('comment', '-') 
            })

        for user in hotspot_users:
            customers.append({
                'id': user.get('id'),
                'name': user.get('name'),
                'mac_address': user.get('mac-address', '-'),
                'type': 'Hotspot',
                'profile': user.get('profile', '-'),
                'expires': user.get('comment', '-')
            })
        
        total_customers = len(customers)
        total_hotspot = len(hotspot_users)
        total_pppoe = len(ppp_secrets)

        context = {
            'customers': customers,
            'total_customers': total_customers,
            'total_hotspot': total_hotspot,
            'total_pppoe': total_pppoe,
        }

        return render(request, 'core/dashboard.html', context)

    except Exception as e:
        # On error, redirect to login and show error
        return redirect('login')

def logout_view(request):
    logout(request)
    return redirect('login')

def create_pppoe_profile_view(request):
    if not request.session.get('router_ip'):
        return redirect('login')
    return render(request, 'core/create_pppoe_profile.html')

def input_pppoe_customer_view(request):
    if not request.session.get('router_ip'):
        return redirect('login')
    return render(request, 'core/input_customer.html')

def create_hotspot_voucher_view(request):
    if not request.session.get('router_ip'):
        return redirect('login')
    return render(request, 'core/create_hotspot_voucher.html')

def edit_route_view(request):
    if not request.session.get('router_ip'):
        return redirect('login')
    return render(request, 'core/edit_route.html')

def monthly_report_view(request):
    if not request.session.get('router_ip'):
        return redirect('login')
    return render(request, 'core/monthly_report.html')
