<%+header%>

<style>
    .add-button {
        display: inline-block;
        padding: 10px 20px;
        width: 7rem;
        height: 2rem;
        background-color: #0056b3;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    .load-button {
        display: inline-block;
        padding: 10px 20px;
        width: 7rem;
        height: 2rem;
        background-color: #00cc06;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    .update-button {
        display: inline-block;
        padding: 10px 20px;
        width: 7rem;
        height: 2rem;
        background-color: #ff1493;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    .delete-button {
        display: inline-block;
        padding: 10px 20px;
        margin-left: 10px;
        width: 7rem;
        height: 2rem;
        background-color: #8e8e8e8e;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
</style>

<p>
    You can register and modify system messages for AI.
</p>

<h2>Create New System Message</h2>

<div style="margin-top: 5px; border-bottom: 1px solid #bbbbbb;">
    <span>TITLE:&nbsp;</span><input id="new-sysmsg-title" type="text" size="15">
    <textarea id="new-sysmsg-data" rows="10" style="margin-top:10px; width:100%; resize:none;"></textarea>
    <div style="margin: 10px;">
        <button id="add-button" class="add-button" type="button">Add</button>
    </div>
</div>

<h2>Load Extra System Message</h2>

<div style="margin-top: 5px; border-bottom: 1px solid #bbbbbb;">
    <span>URL:&nbsp;</span><input id="extra-sysmsg-url" name="extra-sysmsg-url" placeholder=" Please enter the server's url" type="text" style="width:80%;">
    <div style="margin: 10px;">
        <button id="load-button" class="load-button" type="button">Load</button>
    </div>
    <div id="extra-sysmsg" style="display: none;">
        <span>TITLE:&nbsp;</span><input id="extra-sysmsg-title" type="text" size="15">
        <textarea id="extra-sysmsg-data" rows="10" style="margin-top:10px; width:100%; resize:none;"></textarea>
        <div style="margin: 10px;">
            <button id="extra-add-button" class="add-button" type="button">Add</button>
        </div>
    </div>
</div>

<h2 style="margin-top: 20px;">System Message List</h2>
<div id="system-message-list"></div>

<!--TODO: External System Message (via Repository Server) -->

<!--
<div style="margin-top: 5px; border-bottom: 1px solid #bbbbbb;">
    <span>#1 Title:&nbsp;</span><input type="text" size="15">
    <textarea id="system-message-01" rows="10" style="margin-top:10px; width:100%; resize:none;"></textarea>
    <div style="margin-top: 10px;">
        <button type="button">Update</button>
        <button type="button">Delete</button>
    </div>
</div>
-->

<script>
    let name_cnt = 1;

    function create_sysmsg_info(key, value) {

        let is_error = false;
        let is_update = false;

        // Create the container div
        const container = document.createElement('div');
        container.id = key;
        container.style.borderBottom = '1px solid #bbbbbb';

        // Create the span element
        const span = document.createElement('span');
        span.textContent = '#' + name_cnt + ' TITLE: ';

        // Create the input element
        const input = document.createElement('input');
        input.type = 'text';
        input.value = value.title;
        input.size = 15;

        // Create the buttons container
        const buttonsContainer = document.createElement('div');
        //buttonsContainer.id = key;
        buttonsContainer.style.margin = '10px';

        // Create the Update button
        const updateButton = document.createElement('button');
        updateButton.type = 'button';
        updateButton.className = 'update-button'
        updateButton.textContent = 'Update';

        updateButton.addEventListener('click', function() {

            if (input.value.length === 0) {
                alert('Please input system message title');
                return;
            }

            if (textarea.value.length === 0) {
                alert('Please input system message data');
                return;
            }

            if (is_error || is_update) {
                return;
            }

            let update_sysmsg_data = textarea.value;
            update_sysmsg_data = update_sysmsg_data.replace(/"/g, '\\"');

            fetch('<%=build_url("admin", "network", "oasis", "update-sysmsg")%>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({ target: key, title: input.value, message: update_sysmsg_data }),
            })
            .then(response => response.json())
            .then(data => {

                if (data.error) {
                    is_error = true;
                    updateButton.style.backgroundColor = "#FF0000";
                    updateButton.textContent = "ERROR";
                    return;
                }

                is_update = true;
                updateButton.style.backgroundColor = "#FFBF00";
                updateButton.textContent = "Done";
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });

        // Create the textarea element
        const textarea = document.createElement('textarea');
        textarea.id = 'system-message-' + name_cnt;
        textarea.rows = 10;
        textarea.style.marginTop = '10px';
        textarea.style.width = '100%';
        textarea.style.resize = 'none';     
        textarea.value = value.chat.replace(/\\"/g, '"').replace(/\\n/g, '\n');   
         
        textarea.addEventListener('input', function() {
            // After entering something, activate the update button.
            if (is_update) {
                is_update = false;
                updateButton.style.backgroundColor = "#FF1493";
                updateButton.textContent = "Update";
            }
        });
        name_cnt += 1;

        // Create the Delete button
        const deleteButton = document.createElement('button');
        deleteButton.type = 'button';
        deleteButton.className = 'delete-button';
        deleteButton.textContent = 'Delete';

        deleteButton.addEventListener('click', function() {
            fetch('<%=build_url("admin", "network", "oasis", "delete-sysmsg")%>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({ target: key }),
            })
            .then(response => response.json())
            .then(data => {

                if (data.error) {
                    console.error("Error from server:", data.error);
                    return;
                }

                const parent = document.getElementById("system-message-list");
                const child = document.getElementById(key);
                parent.removeChild(child);
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });

        // Append the elements to the container
        container.appendChild(span);
        container.appendChild(input);
        container.appendChild(textarea);
        buttonsContainer.appendChild(updateButton);

        if (key !== "default") {
            buttonsContainer.appendChild(deleteButton);
        }

        container.appendChild(buttonsContainer);

        // Get the parent element by id and append the container to it
        const parentElement = document.getElementById('system-message-list');
        parentElement.appendChild(container);
    }

    document.getElementById('add-button').addEventListener('click', function() {
        
        const new_sysmsg_data = document.getElementById('new-sysmsg-data');
        const new_sysmsg_title = document.getElementById('new-sysmsg-title');

        //console.log(new_sysmsg_title.value);
        //console.log(new_sysmsg_data.value);

        if (new_sysmsg_title.value.length === 0) {
            alert('Please input system message title');
            return;
        }

        if (new_sysmsg_data.value.length === 0) {
            alert('Please input system message data');
            return;
        }


        let add_sysmsg_data =  new_sysmsg_data.value;
        add_sysmsg_data = add_sysmsg_data.replace(/"/g, '\\"');

        fetch('<%=build_url("admin", "network", "oasis", "add-sysmsg")%>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ title: new_sysmsg_title.value, message: add_sysmsg_data }),
        })
        .then(response => response.json())
        .then(data => {

            //console.log(data);

            if (data.error) {
                add_button.disabled = true;
                add_button.style.backgroundColor = "#FF0000";
                add_button.textContent = "ERROR";
                return;
            }

            create_sysmsg_info(data.new_sysmsg_key, {title: new_sysmsg_title.value, chat: new_sysmsg_data.value});

            window.scrollTo({
                top: document.body.scrollHeight,
                behavior: 'smooth'
            });

            new_sysmsg_data.value = '';
        });
    });

    document.getElementById('extra-add-button').addEventListener('click', function() {
        
        const extra_sysmsg_data = document.getElementById('extra-sysmsg-data');
        const extra_sysmsg_title = document.getElementById('extra-sysmsg-title');

        //console.log(extra_sysmsg_title.value);
        //console.log(extra_sysmsg_data.value);

        if (extra_sysmsg_title.value.length === 0) {
            alert('Please input system message title');
            return;
        }

        if (extra_sysmsg_data.value.length === 0) {
            alert('Please input system message data');
            return;
        }


        let add_sysmsg_data =  extra_sysmsg_data.value;
        add_sysmsg_data = add_sysmsg_data.replace(/"/g, '\\"');

        fetch('<%=build_url("admin", "network", "oasis", "add-sysmsg")%>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ title: extra_sysmsg_title.value, message: add_sysmsg_data }),
        })
        .then(response => response.json())
        .then(data => {

            //console.log(data);

            if (data.error) {
                add_button.disabled = true;
                add_button.style.backgroundColor = "#FF0000";
                add_button.textContent = "ERROR";
                return;
            }

            create_sysmsg_info(data.new_sysmsg_key, {title: extra_sysmsg_title.value, chat: extra_sysmsg_data.value});

            window.scrollTo({
                top: document.body.scrollHeight,
                behavior: 'smooth'
            });

            extra_sysmsg_data.value = '';
        });
    });

    document.getElementById('load-button').addEventListener('click', function() {

        const extra_sysmsg_url = document.getElementById('extra-sysmsg-url');
        const extra_sysmsg_container = document.getElementById('extra-sysmsg');
        const extra_sysmsg_textarea = document.getElementById('extra-sysmsg-data');
        //console.log(extra_sysmsg_url.value);

        if (extra_sysmsg_url.value.length === 0) {
            alert('Please input system message server url');
            return;
        }

        fetch('<%=build_url("admin", "network", "oasis", "load-extra-sysmsg")%>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ url: extra_sysmsg_url.value }),
        })
        .then(response => response.json())
        .then(data => {
            //console.log(data);
            extra_sysmsg_textarea.value = data.sysmsg;
            extra_sysmsg_container.style.display = "block";
        });
    });

    document.addEventListener('DOMContentLoaded', function () {
        fetch('<%=build_url("admin", "network", "oasis", "load-sysmsg")%>', {
            method: 'POST',
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                console.error("Error from server:", data.error);
                return;
            }

            create_sysmsg_info("default", data.default);

            Object.entries(data)
                .filter(([key]) => key.startsWith("custom_") && key.match(/^custom_(\d+)$/))
                .sort((a, b) => {
                    const numA = parseInt(a[0].match(/^custom_(\d+)$/)[1], 10);
                    const numB = parseInt(b[0].match(/^custom_(\d+)$/)[1], 10);
                    return numA - numB;
                })
                .forEach(([key, value]) => {
                    create_sysmsg_info(key, value);
                });
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
</script>

<%+footer%>