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

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

        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_constructor.save(values);
        });
    },
    async save(values) {
        const button = document.getElementById('stand-constructor-button');

        const uuid = localStorage.getItem('uuid');
        const URL = `${CONFIG.api}stand/list`;
        await fetch(URL, {
            method: 'POST',
            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 = "Помилка запису";
            })
    }
}