<%+header%>

<style>

    #select-button {
        display: inline-block;
        padding: 10px 20px;
        width: 7rem;
        height: 2rem;
        background-color: #0056b3;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        margin-bottom: 20px;
    }

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

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

    #cancel-button {
        display: block;
        padding: 10px 20px;
        width: 7rem;
        height: 2rem;
        background-color: #8e8e8e8e;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }

    .preview-buttons {
        display: flex;
        justify-content: center;
        gap: 10px;
    }

    #upload-image-container {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        background-color: white;
        border: 1px solid #aaa;
        transform: translate(-50%, -50%);
        border-radius: 8px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        width: 400px;
        text-align: center;
        padding: 20px;
    }
    
    #upload-image-container h3 {
        color: #696969;
    }

    .custom-button:disabled {
        background-color: #4CAF50;
    }

    .icon-container {
      display: flex;
      gap: 10px;
    }
  
    .icon-label {
      cursor: pointer;
      text-align: center;
      margin-right: 15px;
    }
  
    .icon-label img {
      width: 80px;
      height: 80px;
      border-radius: 10px;
      border: 3px solid transparent;
      transition: 0.3s;
      background-color: #FFFFFF;
    }
  
    input[type="radio"]:checked + img {
      border-color: #007bff;
    }
  
    .icon-label input {
      display: none;
    }

    #dropArea {
        display: inline-block;
        width: 80%;
        max-width: 400px;
        padding: 20px;
        margin: 20px auto;
        border: 2px dashed #ccc;
        border-radius: 10px;
        cursor: pointer;
        text-align: center;
    }

    #dropArea.highlight {
        background-color: #e0f7fa;
    }

    .preview {
        margin-top: 20px;
        max-width: 100%;
        height: auto;
    }
</style>

<h2>Select AI Icon</h2>

<div id="oasis-icon-container"></div>

<div style="margin-top: 10px;">
    <button type="button" id="select-button">Select</button>
    <button type="button" id="delete-button">Delete</button>
</div>

<h2>Upload AI Icon</h2>

<div id="dropArea">Drag and Drop Image Upload</div>
<input type="file" id="imageInput" accept="image/*" style="display: none;">

<div id="upload-image-container">
    <h3>Upload this image?</h3>
    <div id="oasis-preview-container"></div>
    <div class="preview-buttons">
        <button type="button" id="upload-button">Upload</button>
        <button type="button" id="cancel-button">Cancel</button>
    </div>
</div>

<script>

    let is_select = false;
    let using_icon_key = ""

    const select_button = document.getElementById('select-button');

    function create_icon_info(key, icon_name, is_using) {
        const resourcePath = '<%= resource %>';
        const iconPath = `${resourcePath}/luci-app-oasis/`;
        const container = document.getElementById('oasis-icon-container');

        const label = document.createElement('label');
        label.classList.add('icon-label');
        label.id = key;

        const input = document.createElement('input');
        input.type = 'radio';

        if (is_using) {
            input.checked = true;
            using_icon_key = key;
        }

        input.name = 'icon';
        input.value = key;
        input.addEventListener('click', function() {
            if (using_icon_key !== key) {
                is_select = false;
                select_button.style.backgroundColor = "#0056b3";
                select_button.textContent = "Select";
            }
        });

        const img = document.createElement('img');
        let decodedIconPath = decodeURIComponent(iconPath + icon_name);
        //img.src = iconPath + icon_name;
        img.src = decodedIconPath;
        img.alt = icon_name;

        label.appendChild(input);
        label.appendChild(img);
        container.appendChild(label);
    }

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

        if (is_select) {
            return;
        }

        const selected_icon = document.querySelector('input[name="icon"]:checked');

        fetch('<%=build_url("admin", "network", "oasis", "select-icon")%>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ using: selected_icon.value }),
        })
        .then(response => response.json())
        .then(data => {

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

            using_icon_key = selected_icon.value;
            select_button.style.backgroundColor = "#FFBF00";
            select_button.textContent = "Done";
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });

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

        if (is_select) {
            return;
        }

        const selected_icon = document.querySelector('input[name="icon"]:checked');
        //console.log(selected_icon.value);

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

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

            const container = document.getElementById('oasis-icon-container');
            const label = document.getElementById(selected_icon.value);
            container.removeChild(label);

        })
        .catch(error => {
            console.error('Error:', error);
        });
    });

    const dropArea = document.getElementById('dropArea');
    const fileInput = document.getElementById('imageInput');
    let selectedFile = null;

    dropArea.addEventListener('click', () => fileInput.click());

    dropArea.addEventListener('dragover', (event) => {
        event.preventDefault();
        dropArea.classList.add('highlight');
    });

    dropArea.addEventListener('dragleave', () => {
        dropArea.classList.remove('highlight');
    });

    dropArea.addEventListener('drop', (event) => {
        event.preventDefault();
        dropArea.classList.remove('highlight');

        const files = event.dataTransfer.files;
        if (files.length > 0) {
            handleFile(files[0]);
        }
    });

    fileInput.addEventListener('change', (event) => {
        const file = event.target.files[0];
        if (file) {
            handleFile(file);
        }
    });

    function handleFile(file) {

        if (!file.type.startsWith('image/')) {
            alert('Please select an image file.');
            return;
        }

        selectedFile = file;
        const reader = new FileReader();
        reader.onload = function(e) {
            const container = document.getElementById('upload-image-container');
            const preview_container = document.getElementById('oasis-preview-container');
            const label = document.createElement('label');
            label.id = "icon-label";
            label.classList.add('icon-label');
            const img = document.createElement('img');
            img.src = e.target.result;
            label.appendChild(img);
            preview_container.appendChild(label);
            container.style.display = 'block';
        };
        reader.readAsDataURL(file);
    }

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

        const reader = new FileReader();

        reader.onload = function(event) {

            const base64Data = event.target.result.split(",")[1];

            fetch('<%=build_url("admin", "network", "oasis", "upload-icon-data")%>', {
                method: "POST",
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({ filename : selectedFile.name, image : base64Data }),
            })
            .then(response => response.json())
            .then(data => {

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

                /* Upload Success */
                create_icon_info(data.key, selectedFile.name, false);
            })
            .catch(error => {
                /* Upload Failure */
                alert("Upload failed");
            });
        };

        reader.readAsDataURL(selectedFile);
        const container = document.getElementById('upload-image-container');
        const preview_container = document.getElementById('oasis-preview-container');
        const image_label = document.getElementById('icon-label');
        preview_container.removeChild(image_label);
        container.style.display = 'none';
    });

    document.getElementById('cancel-button').addEventListener('click', function() {
        const container = document.getElementById('upload-image-container');
        const preview_container = document.getElementById('oasis-preview-container');
        const image_label = document.getElementById('icon-label');
        preview_container.removeChild(image_label);
        container.style.display = 'none';
    });

    document.addEventListener('DOMContentLoaded', function () {
        fetch('<%=build_url("admin", "network", "oasis", "load-icon-info")%>', {
            method: 'POST',
        })
        .then(response => response.json())
        .then(data => {

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

            Object.entries(data.list).forEach(([key, value]) => {
                let is_using = (data.ctrl.using == key) ? true : false;
                create_icon_info(key, value, is_using);
            });
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });

</script>

<%+footer%>