from ._base import *


def get_online_characters_count():
    # Si la BD de personajes (AzerothCore) aún no está disponible/poblada,
    # no rompemos la portada: devolvemos 0 como hace el context_processor.
    try:
        with connections['acore_characters'].cursor() as cursor:
            cursor.execute("SELECT COUNT(*) FROM characters WHERE online = 1")
            result = cursor.fetchone()
            return result[0] if result else 0
    except Exception as e:
        logger.warning("No se pudo contar personajes en línea: %s", e)
        return 0
def check_server_status(host, port):
    if not host or host == "N/A":
        return False
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    try:
        s.connect((host, port))
        s.close()
        return True
    except (socket.timeout, ConnectionRefusedError, socket.gaierror):
        return False
def home_view(request):
    noticias = Noticia.objects.order_by('-fecha_publicacion')[:50]
    online_characters = get_online_characters_count()
    server_selection = ServerSelection.objects.first()
    status = check_server_status(server_selection.address, server_selection.port) if server_selection else None
    game_version = server_selection.expansion if server_selection else 'Unknown'

    context = {
        'noticias': noticias,
        'server': server_selection,
        'status': 'Online' if status else 'Offline',
        'expansion': game_version,
        'online_characters': online_characters,
    }
    return render(request, 'home/home.html', context)
def download_client_view(request):
    download_content = DownloadClientPage.objects.first()
    categorias = ClienteCategoria.objects.all()
    return render(request, 'download/download_client.html', {
        'download_content': download_content,
        'categorias': categorias,
    })
def download_addons_view(request):
    return redirect("https://foro.novawow.com/files/")
def content_creators_view(request):
    content_creator = ContentCreator.objects.first()
    return render(request, 'community/content_creators.html', {'content_creator': content_creator})
def server_status_view(request):
    server_selection = ServerSelection.objects.first()
    if server_selection:
        status = check_server_status(server_selection.address, server_selection.port)
        game_version = server_selection.expansion
    else:
        status = None
        game_version = None

    return render(request, 'server_status/server_status.html', {
        'server': server_selection,
        'status': 'Online' if status else 'Offline',
        'game_version': game_version,
    })
def novawow_realm_view(request):
    return render(request, 'realms/novawow_realm.html')
def contact_us_view(request):
    return render(request, 'contact/contact_us.html')
def legal_notice_view(request):
    return render(request, 'legal/legal_notice.html')
def maintenance_view(request):
    return render(request, 'maintenance/maintenance.html')    
def not_found(request, exception=None):
    return render(request, '404.html', status=404)
def terms_and_conditions_view(request):
    return render(request, 'legal/terms_and_conditions.html')
def privacy_policy_view(request):
    return render(request, 'legal/privacy_policy.html')
def refund_policy_view(request):
    return render(request, 'legal/refund_policy.html')
def cookies_view(request):
    return render(request, 'legal/cookies.html')
def help_view(request):
    # Verificar si el usuario está logueado
    if 'username' not in request.session:
        # Si no está logueado, redirigir al inicio de sesión
        return redirect('index')
    
    # Si está logueado, renderizar la página de ayuda
    return render(request, 'community/help.html')
