const Stand_editor = {
    init: async (id) => {
        let html = await fetch('/lib/pages/stand/editor/index.html').then((response) => response.text());
        app.innerHTML = html;

        const form = document.getElementById('stand-editor-form');

        Stand_editor.setHTML(id);

        form.addEventListener('submit', (event) => {
            event.preventDefault();

            let values = {
                "title": document.getElementById('info-title').value,
                "quantity_sheep": Number(document.getElementById('info-quantity_sheep').value),
                "hour_start": Number(document.getElementById('info-hour_start').value),
                "hour_end": Number(document.getElementById('info-hour_end').value),
                "geo": [Number(document.getElementById('info-geo_lat').value), Number(document.getElementById('info-geo_lng').value)],
                "processing_time": Number(document.getElementById('info-processing_time').value)
            };

            const checkboxes = form.querySelectorAll('input[type="checkbox"][name^="day-"]');
            let week_days = () => {
                let a = [];
                for (const key in checkboxes) {
                    const element = checkboxes[key];
                    if(element.checked) a.push(Number((element.name).replace("day-", "")))
                }
                return a
            }
            values.week_days = week_days();

            console.log(values);

            Stand_editor.save(values, id);
        });
    },

    // Отримання даних з API з авторизацією через UUID
    async loadAPI(URL) {
        let uuid = localStorage.getItem("uuid");
        return await fetch(URL, {
            method: 'GET',
            headers: {
                "Content-Type": "application/json",
                "Authorization": uuid
            }
        }).then((response) => response.json());
    },

    // Встановлення HTML-контенту для редактора залежно від типу об'єкта
    async setHTML(id) {
        let list = await this.loadAPI(`${CONFIG.api}stand/${id}`);

        document.getElementById('info-title').value = list.title;
        document.getElementById('info-quantity_sheep').value = list.quantity_sheep;
        document.getElementById('info-hour_start').value = list.hour_start;
        document.getElementById('info-hour_end').value = list.hour_end;
        document.getElementById('info-geo_lat').value = list.geo[0];
        document.getElementById('info-geo_lng').value = list.geo[1];
        document.getElementById('info-processing_time').value = list.processing_time;

        for (let i = 0; i < list.week_days.length; i++) {
            const element = list.week_days[i];
            document.getElementById(`day-${element}`).checked = true;
        }
    },

    async save(values, id) {
        const button = document.getElementById('stand-editor-button');

        const uuid = localStorage.getItem('uuid');
        const URL = `${CONFIG.api}stand/${id}`;
        await fetch(URL, {
            method: 'PUT',
            headers: {
                "Content-Type": "application/json",
                "Authorization": uuid
            },
            body: JSON.stringify(values)
        })
            .then(response => {
                if (response.status == 200) {
                    console.log({ 'setPack': 'ok' });
                    button.innerText = "Стенд відредаговано";
                    Notifier.success('Стенд відредаговано');

                    Stand_list.list = [];
                    Stand_list.loadAPI();
                    
                    return response.json()
                } else {
                    console.log('err');
                    button.innerText = "Помилка при редагуванні";
                    Notifier.error('Помилка при редагуванні');

                    return
                }
            })
            .then(data => {
                console.log(data);
                // Router.navigate(`/stand/card/${data.id}`);

                setTimeout(() => {
                    button.innerText = "Зберегти";
                }, 3000);
            })
            .catch(err => {
                console.log(err);
                button.innerText = "Помилка при редагуванні";
            })
    }
}