
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User dashboard</title>
</head>

<body>
<button onclick="logout()">Logout</button>

<fieldset>
    <legend>User</legend>
    <pre id="userInfo">-</pre>
    <button onclick="setUserTelegramChatId()">Set Telegram chat id</button>
    <button onclick="sendTestTelegramChat()">Send test message</button>
</fieldset>

<fieldset>
    <legend>Credentials</legend>
    <button onclick="openAddBotCredentialPage()">Add Credential</button>

    <table id="credentialListId">
        <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Type</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</fieldset>

<fieldset>
    <legend>Bots</legend>
    <button id="add-bot" onclick="addBot()">Create Bot</button>

    <table id="bots-table">
        <thead>
        <tr>
            <th></th>
            <th>ID</th>
            <th>User name</th>
            <th>Name</th>
            <th>Environment</th>
            <th>Instrument ID</th>
            <th>Type</th>
            <th>Status</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</fieldset>
</body>

</html>

<style>
    table {
        border-collapse: collapse;
        margin-top: 8px;
        background-color: #fff;
    }

    th,
    td {
        padding: 4px;
        text-align: left;
        border: 1px solid #ddd;
    }

    tr:hover {
        background-color: #f1f1f1;
    }
</style>

<script>

    const token = localStorage.getItem('t')

    const botListElement = document.getElementById('bots-table').getElementsByTagName('tbody')[0]
    const credentialListElement = document.getElementById('credentialListId').getElementsByTagName('tbody')[0]

    document.addEventListener('DOMContentLoaded', function () {
        fetchUserData()
        fetchCredential()
        fetchBots()
    })

    // Fetch the list of bots
    async function fetchBots() {
        try {
            const payload = {
                method: 'GET',
                headers: {
                    "Auth": token
                }
            }
            const response = await fetch('/api/getBots', payload);

            if (response.status == 401) {
                window.open('/', "_self")
                localStorage.setItem('t', '')
                return
            }

            if (!response.ok) {
                response.text().then(text => {
                    alert(JSON.parse(text).msg)
                })
            }
            const json = await response.json()
            const bots = json.data;
            displayBots(bots);
        } catch (error) {
            console.error('Failed to fetch bots:', error);
        }
    }

    async function fetchCredential() {
        try {
            const payload = {
                method: 'GET',
                headers: {
                    "Auth": token
                }
            }
            const response = await fetch('/api/getCredentials', payload);

            if (response.status == 401) {
                window.open('/', "_self")
                localStorage.setItem('t', '')
                return
            }

            if (!response.ok) {
                response.text().then(text => {
                    alert(JSON.parse(text).msg)
                })
            }
            const json = await response.json();
            const credentials = json.data
            displayCredentials(credentials);
        } catch (error) {
            console.error('Failed to fetch bots:', error);
        }
    }

    function displayCredentials(credentials) {
        credentialListElement.innerHTML = ''
        credentials.forEach(credential => {
            const credentialRow = document.createElement('tr')
            credentialRow.innerHTML = `
                <td>${credential.id || "-"}</td>
                <td>${credential.name || "-"}</td>
                <td>${credential.is_demo ? "demo" : "prod"}</td>
                
                <td><button onclick="deleteCredential('${credential.id}')">Delete</button></td>
            `
            credentialListElement.appendChild(credentialRow);
        });
    }

    // Display the list of bots
    function displayBots(bots) {
        botListElement.innerHTML = ''
        bots.forEach(bot => {
            console.log(bot);

            const botRow = document.createElement('tr');
            botRow.innerHTML = `
                <td><button onclick="openBotInfo('${bot.id}')">Dashboard</button></td>
                <td>${bot.id || "-"}</td>
                <td>${bot.username || "-"}</td>
                <td>${bot.name || "-"}</td>
                <td>${bot.credential_is_demo ? "demo" : "prod"}</td>
                <td>${bot.inst_id || "-"}</td>
                <td>${bot.type.toLowerCase() || "-"}</td>
                <td>${bot.is_working ? "working" : "stopped"}</td>
                <td><button onclick="openCloneBot('${bot.id}')">Clone</button></td>
                <td><button ${bot.is_working ? 'disabled' : ''} onclick="deleteBotAlert('${bot.id}', '${bot.name}')">Delete</button></td>
            `
            botListElement.appendChild(botRow)
        })
    }

    // MARK: fetchUserData
    async function fetchUserData() {
        try {
            const payload = {
                method: 'GET',
                headers: {
                    "Auth": token
                }
            }
            const response = await fetch('/api/getUserInfo', payload);

            if (response.status == 401) {
                window.open('/', "_self")
                localStorage.setItem('t', '')
                return
            }

            if (!response.ok) {
                response.text().then(text => {
                    alert(JSON.parse(text).msg)
                })
            }
            const json = await response.json();
            const user = json.data

            const paramStyle = `color:${"#000000"};font-weight: bold`
            document.getElementById('userInfo').innerHTML = `
Username:         <span style="${paramStyle}">${user.username}</span>
Telegram chat id: <span style="${paramStyle}">${user.telegram_chat_id}</span>
`.trim()
        } catch (error) {
            console.error('Failed to fetch bots:', error);
        }
    }

    // MARK: setUserTelegramChatId
    async function setUserTelegramChatId() {
        let chatId = prompt("Please enter Telegram chat Id:");
        if (chatId == null) {
            return
        }
        try {
            const payload = {
                method: 'GET',
                headers: {
                    "Auth": token
                }
            }
            const response = await fetch('/api/setUserTelegramChatId?chatId=' + chatId, payload);

            if (response.status == 401) {
                window.open('/', "_self")
                localStorage.setItem('t', '')
                return
            }

            if (!response.ok) {
                response.text().then(text => {
                    alert(JSON.parse(text).msg)
                })
            } else {
                fetchUserData()
            }
        } catch (error) {
            console.error('Failed to fetch bots:', error);
        }
    }

    // MARK: sendTestTelegramChat
    async function sendTestTelegramChat() {
        try {
            const payload = {
                method: 'GET',
                headers: {
                    "Auth": token
                }
            }
            const response = await fetch('/api/sendTestToTelegramChat', payload);

            if (response.status == 401) {
                window.open('/', "_self")
                localStorage.setItem('t', '')
                return
            }

            if (!response.ok) {
                response.text().then(text => {
                    alert(JSON.parse(text).msg)
                })
            }
        } catch (error) {
            console.error('Failed to fetch bots:', error);
        }
    }

    function openCloneBot(botId) {
        window.open('/createBot?botId=' + botId, '_self');
    }

    function deleteBotAlert(botId, name) {
        if (confirm(`Are you sure that you want to delete bot ${name}?`)) {
            deleteBot(botId)
        }
    }

    // Add a new bot
    function addBot() {
        window.open('/createBot', '_self');
    }

    function openAddBotCredentialPage() {
        window.open('/addCredential', '_blank', 'width=800,height=400,top=128,left=128'); // Opens in a new tab
    }

    function openBotInfo(botId) {
        window.open('/botDashboard' + '?botId=' + botId, "_self")
    }

    async function deleteCredential(credentialId) {
        if (confirm(`Are you sure that you want to delete credential ${credentialId}?`)) {
            const data = {
                credentialId: parseInt(credentialId)
            }
            try {
                const response = await fetch('/api/deleteCredential', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        "Auth": token
                    },
                    body: JSON.stringify(data)
                });

                if (!response.ok) {
                    response.text().then(text => {
                        alert(JSON.parse(text).msg)
                    })
                } else {
                    console.log(response.json());
                }
                await fetchCredential();
            } catch (error) {
                console.error('Error adding bot:', error);
            }
        }
    }

    async function deleteBot(botId) {
        const data = {
            bot_id: parseInt(botId)
        }

        try {
            const response = await fetch('/api/deleteBot', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    "Auth": token
                },
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                response.text().then(text => {
                    alert(JSON.parse(text).msg)
                })
            } else {
                console.log(response.json());
            }
            await fetchBots();
        } catch (error) {
            console.error('Error adding bot:', error);
        }
    }

    async function logout() {
        if (confirm(`Are you sure that you want to logout?`)) {
            const response = await fetch('/api/logout', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    "Auth": token
                }
            });

            if (!response.ok) {
                response.text().then(text => {
                    alert(JSON.parse(text).msg)
                })
            } else {
                localStorage.setItem('t', "")
                window.open('/', "_self")
            }
        }
    }
</script>