{% extends "base.html" %}

{% block title %}Databases - {{ cluster_name }} - AtlasUI{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h1><i class="bi bi-database"></i> Databases - <span id="clusterNameDisplay">{{ cluster_name }}</span></h1>
            <button class="btn btn-outline-secondary btn-sm" onclick="window.history.back()">
                <i class="bi bi-arrow-left"></i> Back
            </button>
        </div>

        <script>
            const CLUSTER_NAME = "{{ cluster_name }}";
        </script>

        <!-- Login Form (shown initially) -->
        <div id="loginSection" class="card">
            <div class="card-body">
                <h5 class="card-title"><i class="bi bi-key"></i> Login to Cluster</h5>
                <p class="text-muted">Enter your database credentials to view the databases in this cluster.</p>

                <div id="loginError" class="alert alert-danger d-none"></div>

                <form id="loginForm">
                    <input type="hidden" id="clusterConnectionString" />

                    <div class="mb-3">
                        <label for="username" class="form-label">Username</label>
                        <input type="text" class="form-control" id="username" required autocomplete="username">
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Password</label>
                        <input type="password" class="form-control" id="password" required autocomplete="current-password">
                    </div>
                    <button type="submit" class="btn btn-primary" id="loginBtn">
                        <i class="bi bi-box-arrow-in-right"></i> Login
                    </button>
                </form>
            </div>
        </div>

        <!-- Databases List (shown after successful login) -->
        <div id="databasesSection" class="d-none">
            <div class="alert alert-success mb-3">
                <i class="bi bi-check-circle"></i> Successfully connected! Found <span id="dbCount">0</span> database(s)
            </div>

            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>Database Name</th>
                            <th>Collections</th>
                            <th>Indexes</th>
                            <th>Size on Disk</th>
                        </tr>
                    </thead>
                    <tbody id="databasesTableBody">
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Loading indicator -->
        <div id="loadingIndicator" class="text-center my-5 d-none">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Connecting to cluster...</p>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<style>
    h1 {
        font-size: 1.25rem;
    }
</style>

<script>
let clusterData = null;

document.addEventListener('DOMContentLoaded', function() {
    loadClusterInfo();

    document.getElementById('loginForm').addEventListener('submit', function(e) {
        e.preventDefault();
        loginToCluster();
    });
});

async function loadClusterInfo() {
    try {
        // Fetch all clusters to find the one matching CLUSTER_NAME
        const response = await fetch('/api/clusters');
        // We need to iterate through all organizations and projects to find the cluster
        // For now, we'll try to fetch from a specific endpoint
        // This is a simplified approach - you might need to adjust based on your API structure

        // Try to find cluster by searching through all clusters
        const orgsResponse = await fetch('/api/organizations/?itemsPerPage=500');
        const orgsData = await orgsResponse.json();

        for (let org of orgsData.results || []) {
            const projectsResponse = await fetch(`/api/organizations/${org.id}/projects?itemsPerPage=500`);
            if (projectsResponse.ok) {
                const projectsData = await projectsResponse.json();

                for (let project of projectsData.results || []) {
                    const clustersResponse = await fetch(`/api/clusters/${project.id}?itemsPerPage=500`);
                    if (clustersResponse.ok) {
                        const clustersData = await clustersResponse.json();
                        const cluster = (clustersData.results || []).find(c => c.name === CLUSTER_NAME);

                        if (cluster) {
                            clusterData = cluster;
                            document.getElementById('clusterConnectionString').value = cluster.connectionStrings?.standardSrv || '';
                            return;
                        }
                    }
                }
            }
        }

        // If we couldn't find the cluster, show an error
        if (!clusterData) {
            document.getElementById('loginError').textContent = `Cluster "${CLUSTER_NAME}" not found`;
            document.getElementById('loginError').classList.remove('d-none');
        }
    } catch (err) {
        console.error('Error loading cluster info:', err);
        document.getElementById('loginError').textContent = 'Failed to load cluster information';
        document.getElementById('loginError').classList.remove('d-none');
    }
}

async function loginToCluster() {
    const loginBtn = document.getElementById('loginBtn');
    const loginError = document.getElementById('loginError');
    const loginSection = document.getElementById('loginSection');
    const databasesSection = document.getElementById('databasesSection');
    const loadingIndicator = document.getElementById('loadingIndicator');

    const connectionString = document.getElementById('clusterConnectionString').value;
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    if (!connectionString) {
        loginError.textContent = 'Cluster connection string not found';
        loginError.classList.remove('d-none');
        return;
    }

    if (!username || !password) {
        loginError.textContent = 'Please enter username and password';
        loginError.classList.remove('d-none');
        return;
    }

    // Hide error messages
    loginError.classList.add('d-none');

    // Show loading state
    loginBtn.disabled = true;
    loginBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Connecting...';
    loadingIndicator.classList.remove('d-none');

    try {
        const response = await fetch('/api/clusters/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                connection_string: connectionString,
                username: username,
                password: password
            })
        });

        const data = await response.json();

        if (response.ok) {
            // Hide login section and loading
            loginSection.classList.add('d-none');
            loadingIndicator.classList.add('d-none');

            // Update database count
            document.getElementById('dbCount').textContent = data.total;

            // Populate databases table
            const tbody = document.getElementById('databasesTableBody');
            tbody.innerHTML = '';

            data.databases.forEach(db => {
                const row = document.createElement('tr');
                if (db.error) {
                    row.innerHTML = `
                        <td><strong>${db.name}</strong></td>
                        <td colspan="3" class="text-danger small">${db.error}</td>
                    `;
                } else {
                    row.innerHTML = `
                        <td><strong>${db.name}</strong></td>
                        <td>${db.collections || 0}</td>
                        <td>${db.indexes || 0}</td>
                        <td>${formatBytes(db.sizeOnDisk || 0)}</td>
                    `;
                }
                tbody.appendChild(row);
            });

            // Show databases section
            databasesSection.classList.remove('d-none');

        } else {
            loadingIndicator.classList.add('d-none');
            loginError.textContent = data.detail || 'Failed to connect to cluster';
            loginError.classList.remove('d-none');
        }

    } catch (err) {
        console.error('Login error:', err);
        loadingIndicator.classList.add('d-none');
        loginError.textContent = 'Failed to connect to cluster: ' + err.message;
        loginError.classList.remove('d-none');
    } finally {
        // Reset button state
        loginBtn.disabled = false;
        loginBtn.innerHTML = '<i class="bi bi-box-arrow-in-right"></i> Login';
    }
}

function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
</script>
{% endblock %}
