from ._base import *
from .auth import authenticate, get_user_from_acore


def rename_guild_view(request):
    username = request.session.get('username')
    if not username:
        return redirect('login')

    user_data = get_user_from_acore(username)
    if not user_data:
        return redirect('login')

    user_id = user_data['id']
    email = user_data['email']
    
    security_token = SecurityToken.objects.filter(user_id=user_id).first()
    guild_settings, created = GuildRenameSettings.objects.get_or_create(defaults={'cost': 10})
    rename_cost = guild_settings.cost

    with connections['acore_characters'].cursor() as cursor:
        cursor.execute("""
            SELECT g.guildid, g.name, gm.rank, c.name
            FROM guild g
            JOIN guild_member gm ON g.guildid = gm.guildid
            JOIN characters c ON c.guid = gm.guid
            WHERE c.account = %s AND gm.rank = 0
        """, [user_id])
        guild_leader_data = cursor.fetchall()

    if not guild_leader_data:
        return JsonResponse({'success': False, 'message': '<span class="red-form-response">Error: No tienes personajes que sean Maestros de Hermandad en tu cuenta.</span>'})
    
    with connections['acore_auth'].cursor() as cursor:
        cursor.execute("""
            SELECT id, email, last_ip FROM account WHERE username = %s
        """, [username])
        account_info = cursor.fetchone()

    if not account_info:
        return JsonResponse({'success': False, 'message': '<span class="red-form-response">Error: Cuenta no encontrada.</span>'})

    account_id, email, acore_ip = account_info
    client_ip = request.META.get('REMOTE_ADDR', '')

    if request.method == 'POST':
        old_guild_name = request.POST.get('old-guild-name', '').strip()
        new_guild_name = request.POST.get('new-guild-name', '').strip()
        conf_new_guild_name = request.POST.get('conf-new-guild-name', '').strip()
        current_password = request.POST.get('cur-password', '').strip()
        token = request.POST.get('security-token', '').strip()

        if not old_guild_name or not new_guild_name or not conf_new_guild_name or not current_password or not token:
            return JsonResponse({'success': False, 'message': '<span class="red-form-response">Por favor, completa todos los campos.</span>'})

        if not authenticate(email, current_password):
            return JsonResponse({'success': False, 'message': '<span class="red-form-response">La contraseña actual es incorrecta.</span>'})
            
        if not security_token or security_token.token != token:
            return JsonResponse({'success': False, 'message': '<span class="red-form-response">Token de seguridad incorrecto.</span>'})

        if new_guild_name != conf_new_guild_name:
            return JsonResponse({'success': False, 'message': '<span class="red-form-response">Los nombres nuevos no coinciden.</span>'})

        success_url = request.build_absolute_uri(reverse('guild-success'))
        cancel_url = request.build_absolute_uri(reverse('guild-cancel'))

        stripe_response = create_checkout_session(
            account_id=user_id,
            username=username,
            email=email,
            acore_ip=acore_ip,
            amount=rename_cost,
            character_name=old_guild_name,
            success_url=success_url,
            cancel_url=cancel_url,
            product_name=f"Renombrar hermandad: {old_guild_name} → {new_guild_name}"
        )

        if stripe_response["success"]:
            request.session['guild_rename'] = {
                'old_name': old_guild_name,
                'new_name': new_guild_name
            }
            return JsonResponse({
                'success': True,
                'session_id': stripe_response["session_id"],
                'stripe_public_key': settings.STRIPE_PUBLIC_KEY
            })
        else:
            return JsonResponse({'success': False, 'message': f'Error al iniciar el pago: {stripe_response["error"]}'})

    return render(request, 'account/rename_guild.html', {
        'guild_leader_data': guild_leader_data,
        'rename_cost': rename_cost,
        'guild_names': [g[1] for g in guild_leader_data],
    })
@require_paid_stripe()
def guild_rename_success_view(request):
    # Obtener los datos de la sesión
    guild_rename_data = request.session.get('guild_rename')
    if not guild_rename_data:
        return redirect('rename-cancel')  # Redirigir si no hay datos de renombrado

    old_guild_name = guild_rename_data.get('old_name')
    new_guild_name = guild_rename_data.get('new_name')

    if not old_guild_name or not new_guild_name:
        return redirect('rename-cancel')  # Redirigir si faltan datos

    # Ejecutar el comando SOAP
    command = f".guild rename {old_guild_name} {new_guild_name}"
    response = execute_soap_command(command)

    # Limpiar la sesión después de la ejecución
    request.session.pop('guild_rename', None)

    if response is None or response.strip() == "":
        message = f"La Hermandad '{old_guild_name}' ha cambiado su nombre a '{new_guild_name}'. Cierra sesión y vuelve a entrar para que los cambios se reflejen en el juego."
        return render(request, 'account/guild_rename_success.html', {'message': message})
    else:
        return render(request, 'account/guild_rename_success.html', {'message': f"Error: {response}"})
def guild_rename_cancel_view(request):
    """
    Vista para la página de intercambio de puntos.
    """
    return render(request, 'account/guild_rename_cancel.html')    
