{% extends "base_config.html" %}
{% block content %}

<div class="page">
    <div id="content" class="section">
        <h2 class="section-title">Content</h2>
        <button id="compute-index-size" class="card-button" onclick="getIndexedDataSize()">
            Data Usage
        </button>
        <p id="indexed-data-size" class="card-description"></p>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/computer.png" alt="Computer">
                    <h3 id="card-title-computer" class="card-title">
                        Files
                        <img id="configured-icon-computer"
                            style="display: {% if not current_model_state.computer %}none{% endif %}"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured">
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Manage files from your computer</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content-source/computer">
                        {% if current_model_state.computer %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    <div id="clear-computer" class="card-action-row"
                        style="display: {% if not current_model_state.computer %}none{% endif %}">
                        <button class="card-button" onclick="clearContentType('computer')">
                            Disable
                        </button>
                    </div>
                </div>
            </div>
             <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/github.svg" alt="Github">
                    <h3 class="card-title">
                        Github
                        <img id="configured-icon-github"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured"
                            style="display: {% if not current_model_state.github %}none{% endif %}">
                    </h3>
                </div>
                <div class="card-description-row">
                <p class="card-description">Set repositories to index</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content-source/github">
                        {% if current_model_state.github %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    <div id="clear-github"
                        class="card-action-row"
                        style="display: {% if not current_model_state.github %}none{% endif %}">
                        <button class="card-button" onclick="clearContentType('github')">
                            Disable
                        </button>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/notion.svg" alt="Notion">
                    <h3 class="card-title">
                        Notion
                        <img id="configured-icon-notion"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured"
                            style="display: {% if not current_model_state.notion %}none{% endif %}">
                    </h3>
                </div>
                <div class="card-description-row">
                    <p class="card-description">Sync your Notion pages</p>
                </div>
                <div class="card-action-row">
                    <a class="card-button" href="/config/content-source/notion">
                        {% if current_model_state.notion %}
                            Update
                        {% else %}
                            Setup
                        {% endif %}
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                    <div id="clear-notion"
                        class="card-action-row"
                        style="display: {% if not current_model_state.notion %}none{% endif %}">
                        <button class="card-button" onclick="clearContentType('notion')">
                            Disable
                        </button>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/web.svg" alt="Language">
                    <h3 class="card-title">
                        Language
                    </h3>
                </div>
                <div class="card-description-row">
                    <select id="search-models">
                        {% for option in search_model_options %}
                            <option value="{{ option.id }}" {% if option.id == selected_search_model_config %}selected{% endif %}>{{ option.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="card-action-row">
                    <button id="save-search-model" class="card-button happy" onclick="updateSearchModel()">
                        Save
                    </button>
                </div>
            </div>
        </div>
        <div class="general-settings section">
            <div id="status" style="display: none;"></div>
        </div>
        <div class="section finalize-actions general-settings">
            <div class="section-cards">
                <div class="finalize-buttons">
                    <button id="configure" type="submit" title="Update index with the latest changes">💾 Save All</button>
                </div>
                <div class="finalize-buttons">
                    <button id="reinitialize" type="submit" title="Regenerate index from scratch">🔄 Reinitialize</button>
                </div>
            </div>
        </div>
    </div>
    <div id ="features" class="section">
        <h2 class="section-title">Features</h2>
        <div id="features-hint-text"></div>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/chat.svg" alt="Chat">
                    <h3 class="card-title">
                        Chat
                    </h3>
                </div>
                <div class="card-description-row">
                    <select id="chat-models">
                        {% for option in conversation_options %}
                            <option value="{{ option.id }}" {% if option.id == selected_conversation_config %}selected{% endif %}>{{ option.chat_model }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="card-action-row">
                    <button id="save-model" class="card-button happy" onclick="updateChatModel()">
                        Save
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div id="clients" class="section">
        <h2 class="section-title">Clients</h2>
        <div id="clients-api" class="api-settings">
            <div class="card-title-row">
                <img class="card-icon" src="/static/assets/icons/key.svg" alt="API Key">
                <h3 class="card-title">API Keys</h3>
            </div>
            <div class="card-description-row">
                <p id="api-settings-card-description" class="card-description">Manage access from your client apps to Khoj</p>
            </div>
            <table id="api-settings-keys-table">
                <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Key</th>
                    <th scope="col">Actions</th>
                </tr>
                </thead>
                <tbody id="api-key-list"></tbody>
            </table>
            <div class="card-action-row">
                <button class="card-button happy" id="generate-api-key" onclick="generateAPIKey()">
                    Generate API Key
                </button>
            </div>
        </div>
    </div>
    {% if billing_enabled %}
    <div id="billing" class="section">
        <h2 class="section-title">Billing</h2>
        <div class="section-cards">
            <div class="card">
                <div class="card-title-row">
                    <img class="card-icon" src="/static/assets/icons/credit-card.png" alt="Credit Card">
                    <h3 class="card-title">
                        <span>Subscription</span>
                        <img id="configured-icon-subscription"
                            style="display: {% if subscription_state == 'trial' or subscription_state == 'expired' %}none{% endif %}"
                            class="configured-icon"
                            src="/static/assets/icons/confirm-icon.svg"
                            alt="Configured">
                    </h3>
                </div>
                <div class="card-description-row">
                    <p id="trial-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'trial' %}none{% endif %}">
                        Subscribe to Khoj Cloud. See <a href="https://khoj.dev/pricing">pricing</a> for details.
                    </p>
                    <p id="unsubscribe-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'subscribed' %}none{% endif %}">
                       You are <b>subscribed</b> to Khoj Cloud. Subscription will <b>renew</b> on <b>{{ subscription_renewal_date }}</b>
                    </p>
                    <p id="resubscribe-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'unsubscribed' %}none{% endif %}">
                       You are <b>subscribed</b> to Khoj Cloud. Subscription will <b>expire</b> on <b>{{ subscription_renewal_date }}</b>
                    </p>
                    <p id="expire-description"
                       class="card-description"
                       style="display: {% if subscription_state != 'expired' %}none{% endif %}">
                       Subscribe to Khoj Cloud. Subscription <b>expired</b> on <b>{{ subscription_renewal_date }}</b>
                    </p>
                </div>
                <div class="card-action-row">
                    <button id="unsubscribe-button"
                            class="card-button"
                            onclick="unsubscribe()"
                            style="display: {% if subscription_state != 'subscribed' %}none{% endif %};">
                        Unsubscribe
                    </button>
                    <button id="resubscribe-button"
                            class="card-button happy"
                            onclick="resubscribe()"
                            style="display: {% if subscription_state != 'unsubscribed' %}none{% endif %};">
                        Resubscribe
                    </button>
                    <a id="subscribe-button"
                       class="card-button happy"
                       href="{{ khoj_cloud_subscription_url }}?prefilled_email={{ username }}"
                       style="display: {% if subscription_state == 'subscribed' or subscription_state == 'unsubscribed' %}none{% endif %};">
                        Subscribe
                        <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>
                    </a>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
    <div class="section"></div>
    </div>
    <div class="section" id="notification-banner-parent">
        <div id="notification-banner"></div>
    </div>
</div>
<script>

    function updateChatModel() {
        const chatModel = document.getElementById("chat-models").value;
        const saveModelButton = document.getElementById("save-model");
        saveModelButton.disabled = true;
        saveModelButton.innerHTML = "Saving...";

        fetch('/api/config/data/conversation/model?id=' + chatModel, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                saveModelButton.innerHTML = "Save";
                saveModelButton.disabled = false;
            } else {
                saveModelButton.innerHTML = "Error";
                saveModelButton.disabled = false;
            }
        })
    };

    function updateSearchModel() {
        const searchModel = document.getElementById("search-models").value;
        const saveSearchModelButton = document.getElementById("save-search-model");
        saveSearchModelButton.disabled = true;
        saveSearchModelButton.innerHTML = "Saving...";

        fetch('/api/config/data/search/model?id=' + searchModel, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                saveSearchModelButton.innerHTML = "Save";
                saveSearchModelButton.disabled = false;
            } else {
                saveSearchModelButton.innerHTML = "Error";
                saveSearchModelButton.disabled = false;
            }

            let notificationBanner = document.getElementById("notification-banner");
            notificationBanner.innerHTML = "When updating the language model, be sure to delete all your saved content and re-initialize.";
            notificationBanner.style.display = "block";
            setTimeout(function() {
                notificationBanner.style.display = "none";
            }, 5000);
        })
    };

    function clearContentType(content_source) {
        fetch('/api/config/data/content-source/' + content_source, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                document.getElementById("configured-icon-" + content_source).style.display = "none";
                document.getElementById("clear-" + content_source).style.display = "none";
            } else {
                document.getElementById("configured-icon-" + content_source).style.display = "";
                document.getElementById("clear-" + content_source).style.display = "";
            }
        })
    };

    function unsubscribe() {
        fetch('/api/subscription?operation=cancel&email={{username}}', {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
               document.getElementById("unsubscribe-description").style.display = "none";
               document.getElementById("unsubscribe-button").style.display = "none";

               document.getElementById("resubscribe-description").style.display = "";
               document.getElementById("resubscribe-button").style.display = "";

             }
        })
    }

    function resubscribe() {
        fetch('/api/subscription?operation=resubscribe&email={{username}}', {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
               document.getElementById("resubscribe-description").style.display = "none";
               document.getElementById("resubscribe-button").style.display = "none";

               document.getElementById("unsubscribe-description").style.display = "";
               document.getElementById("unsubscribe-button").style.display = "";
            }
        })
    }

    var configure = document.getElementById("configure");
    configure.addEventListener("click", function(event) {
        event.preventDefault();
        updateIndex(
            force=false,
            successText="Saved!",
            errorText="Unable to configure. Raise issue on Khoj <a href='https://github.com/khoj-ai/khoj/issues'>Github</a> or <a href='https://discord.gg/BDgyabRM6e'>Discord</a>.",
            button=configure,
            loadingText="Saving...",
            emoji="💾");
    });

    var reinitialize = document.getElementById("reinitialize");
    reinitialize.addEventListener("click", function(event) {
        event.preventDefault();
        updateIndex(
            force=true,
            successText="Reinitialized!",
            errorText="Unable to reinitialize. Raise issue on Khoj <a href='https://github.com/khoj-ai/khoj/issues'>Github</a> or <a href='https://discord.gg/BDgyabRM6e'>Discord</a>.",
            button=reinitialize,
            loadingText="Reinitializing...",
            emoji="🔄");
    });

    function updateIndex(force, successText, errorText, button, loadingText, emoji) {
        const csrfToken = document.cookie.split('; ').find(row => row.startsWith('csrftoken'))?.split('=')[1];
        const original_html = button.innerHTML;
        button.disabled = true;
        button.innerHTML = emoji + " " + loadingText;
        fetch('/api/update?&client=web&force=' + force, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.detail != null) {
                throw new Error(data.detail);
            }

            document.getElementById("status").style.display = "none";

            button.disabled = false;
            button.innerHTML = `✅ ${successText}`;
            setTimeout(function() {
                button.innerHTML = original_html;
            }, 2000);
        })
        .catch((error) => {
            console.error('Error:', error);
            document.getElementById("status").innerHTML = emoji + " " + errorText
            document.getElementById("status").style.display = "block";
            button.disabled = false;
            button.innerHTML = '⚠️ Unsuccessful';
            setTimeout(function() {
                button.innerHTML = original_html;
            }, 2000);
        });

        content_sources = ["computer", "github", "notion"];
        content_sources.forEach(content_source => {
            fetch(`/api/config/data/${content_source}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.length > 0) {
                    document.getElementById("configured-icon-" + content_source).style.display = "";
                    document.getElementById("clear-" + content_source).style.display = "";
                } else {
                    document.getElementById("configured-icon-" + content_source).style.display = "none";
                    document.getElementById("clear-" + content_source).style.display = "none";
                }
            });
        });
    }

    function generateAPIKey() {
        const apiKeyList = document.getElementById("api-key-list");
        fetch('/auth/token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
        })
        .then(response => response.json())
        .then(tokenObj => {
            apiKeyList.innerHTML += generateTokenRow(tokenObj);
        });
    }

    function copyAPIKey(token) {
        // Copy API key to clipboard
        navigator.clipboard.writeText(token);
        // Flash the API key copied message
        const copyApiKeyButton = document.getElementById(`api-key-${token}`);
        original_html = copyApiKeyButton.innerHTML
        setTimeout(function() {
            copyApiKeyButton.innerHTML = "✅ Copied!";
            setTimeout(function() {
                copyApiKeyButton.innerHTML = original_html;
            }, 1000);
        }, 100);
    }

    function deleteAPIKey(token) {
        const apiKeyList = document.getElementById("api-key-list");
        fetch(`/auth/token?token=${token}`, {
            method: 'DELETE',
        })
        .then(response => {
            if (response.ok) {
                const apiKeyItem = document.getElementById(`api-key-item-${token}`);
                apiKeyList.removeChild(apiKeyItem);
            }
        });
    }

    function generateTokenRow(tokenObj) {
        let token = tokenObj.token;
        let tokenName = tokenObj.name;
        let truncatedToken = token.slice(0, 4) + "..." + token.slice(-4);
        let tokenId = `${tokenName}-${truncatedToken}`;
        return `
            <tr id="api-key-item-${token}">
                <td><b>${tokenName}</b></td>
                <td id="api-key-${token}">${truncatedToken}</td>
                <td>
                    <img onclick="copyAPIKey('${token}')" class="configured-icon api-key-action enabled" src="/static/assets/icons/copy-solid.svg" alt="Copy API Key" title="Copy API Key">
                    <img onclick="deleteAPIKey('${token}')" class="configured-icon api-key-action enabled" src="/static/assets/icons/trash-solid.svg" alt="Delete API Key" title="Delete API Key">
                </td>
            </tr>
        `;

    }

    function listApiKeys() {
        const apiKeyList = document.getElementById("api-key-list");
        fetch('/auth/token')
            .then(response => response.json())
            .then(tokens => {
                apiKeyList.innerHTML = tokens.map(generateTokenRow).join("");
            });
    }

    function getIndexedDataSize() {
        document.getElementById("indexed-data-size").innerHTML = "Calculating...";
        fetch('/api/config/index/size')
            .then(response => response.json())
            .then(data => {
                document.getElementById("indexed-data-size").innerHTML = data.indexed_data_size_in_mb + " MB used";
            });
    }

    // List user's API keys on page load
    listApiKeys();

    function removeFile(path) {
        fetch('/api/config/data/file?filename=' + path, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status == "ok") {
                getAllFilenames();
            }
        })
    }
</script>
{% endblock %}
