from ._base import *
from .account import get_account_id


def format_datetime(timestamp):
    if timestamp:
        return datetime.utcfromtimestamp(timestamp).strftime('%d-%m-%Y %H:%M:%S')
    return "No disponible"


def get_ban_history(account_id):
    # Consulta de baneos de la cuenta
    with connections['acore_auth'].cursor() as cursor:
        cursor.execute("""
            SELECT bandate, unbandate, banreason, active, account.username
            FROM account_banned
            JOIN account ON account_banned.id = account.id
            WHERE account_banned.id = %s
        """, [account_id])
        account_bans = cursor.fetchall()

    # Formatear las fechas
    account_bans = [(format_datetime(ban[0]), format_datetime(ban[1]), ban[2], ban[3], ban[4]) for ban in account_bans]
    
    # Consulta de baneos de los personajes asociados a la cuenta
    with connections['acore_characters'].cursor() as cursor:
        cursor.execute("""
            SELECT bandate, unbandate, banreason, active, characters.name
            FROM character_banned
            JOIN characters ON character_banned.guid = characters.guid
            WHERE characters.account = %s
        """, [account_id])
        character_bans = cursor.fetchall()

    # Formatear las fechas
    character_bans = [(format_datetime(ban[0]), format_datetime(ban[1]), ban[2], ban[3], ban[4]) for ban in character_bans]

    return account_bans, character_bans
def calculate_unmute_date(mute_date, mute_duration):
    if isinstance(mute_date, int):
        mute_date = datetime.fromtimestamp(mute_date)
    return mute_date + timedelta(seconds=mute_duration)
def ban_history_view(request):
    # Verificar si el usuario tiene un `username` en la sesión
    username = request.session.get('username')
    if not username:
        return redirect('login')
    
    # Obtener el account_id a partir del username
    account_id = get_account_id(username)
    if not account_id:
        return redirect('login')  # O redirigir a otra página si no se encuentra el account_id

    print(f"Account ID: {account_id}")  # Depurar el account_id
    
    account_bans, character_bans = get_ban_history(account_id)

    def _row(b, origen):
        return {
            'fecha_baneo': b[0] or 'No disponible',
            'fecha_desbaneo': b[1] or 'No disponible',
            'motivo': b[2],
            'estado': 'Activo' if b[3] == 1 else 'Inactivo',
            'origen': f'{origen}: {b[4]}',
        }

    ban_rows = ([_row(b, 'Cuenta') for b in account_bans]
                + [_row(b, 'Personaje') for b in character_bans])

    return render(request, 'account/ban_history.html', {
        'account_bans': account_bans,
        'character_bans': character_bans,
        'ban_rows': ban_rows,
        'now': datetime.now(),
    })
def security_history_view(request):
    username = request.session.get('username')
    if not username:
        return redirect('login')  # Si no está autenticado, redirigir al login

    # Obtener los últimos 20 intentos de inicio de sesión
    login_attempts = LoginAttempt.objects.filter(username=username).order_by('-timestamp')[:20]

    login_attempts_data = [
        {
            'username': a.username,
            'status': a.status,
            'ip_address': a.ip_address,
            'timestamp': a.timestamp.strftime('%d-%m-%Y %H:%M:%S') if a.timestamp else '',
        }
        for a in login_attempts
    ]

    return render(request, 'account/security_history.html', {
        'login_attempts': login_attempts,
        'login_attempts_data': login_attempts_data,
    })
