{% load i18n %}
{% load evelinks %}
{% load humanize %}
<div class="card card-body mt-2 rounded">
    <!-- Ore Survey Table -->
    <div id="ore-survey-tables"></div>
    <template id="ore-survey-table-template">
        <div class="table-responsive mb-3">
            <table class="table table-striped table-hover w-100 ore-survey-table" id="ore-survey-table">
                <thead>
                    <tr>
                        <th class="w-auto">{% translate "" %}</th>
                        <th class="w-auto">{% translate "Ore" %}</th>
                        <th class="w-auto">{% translate "Units" %}</th>
                        <th class="w-auto">{% translate "Volume Left" %}</th>
                        <th class="w-auto">{% translate "Price" %}</th>
                        <th class="w-auto">{% translate "Price Compressed" %}</th>
                        <th class="w-auto">{% translate "Timestamp" %}</th>
                    </tr>
                </thead>
                <tbody></tbody>
                <tfoot></tfoot>
            </table>
        </div>
    </template>
    <template id="ore-survey-heading-template">
        <h6 class="mb-2 mt-3 text-muted ore-survey-heading"></h6>
    </template>
</div>

<script>
    $(document).ready(function() {
        const tablesContainer = document.getElementById('ore-survey-tables');
        const tableTemplate = document.getElementById('ore-survey-table-template');
        const headingTemplate = document.getElementById('ore-survey-heading-template');

        const createSurveyDataTable = (tableElement, tableData) => {
            return new DataTable(tableElement, {
                data: tableData,
                language: aaBeltRadarSettings.dataTables.language,
                layout: aaBeltRadarSettings.dataTables.layout,
                ordering: aaBeltRadarSettings.dataTables.ordering,
                columnControl: aaBeltRadarSettings.dataTables.columnControl,
                order: [[5, 'desc']],
                columnDefs: [
                    {
                        orderable: false,
                        targets: 0,
                        columnControl: [
                            {target: 0, content: []},
                            {target: 1, content: []}
                        ]
                    },
                    {
                        targets: [2,3,4,5],
                        type: 'num'
                    },
                ],
                columns: [
                    {
                        data: {
                            display: (data) => data.portrait,
                            sort: (data) => data.name,
                            filter: (data) => data.name,
                        }
                    },
                    {
                        data: {
                            display: (data) => data.name,
                            sort: (data) => data.name,
                            filter: (data) => data.name,
                        }
                    },
                    {
                        data: {
                            display: (data) => `${data.units.toLocaleString()}`,
                            sort: (data) => data.units,
                            filter: (data) => data.units,
                        }
                    },
                    {
                        data: {
                            display: (data) => `${data.volume_m3.toLocaleString()} m³`,
                            sort: (data) => data.volume_m3,
                            filter: (data) => data.volume_m3,
                        }
                    },
                    {
                        data: {
                            display: (data) => numberFormatter({
                                value: data.price_isk,
                                language: aaBeltRadarSettings.locale,
                                options: {
                                    style: 'currency',
                                    currency: 'ISK',
                                    maximumFractionDigits: 0
                                }
                            }),
                            sort: (data) => data.price_isk ?? 0,
                            filter: (data) => data.price_isk ?? 0,
                        }
                    },
                    {
                        data: {
                            display: (data) => numberFormatter({
                                value: data.price_compressed,
                                language: aaBeltRadarSettings.locale,
                                options: {
                                    style: 'currency',
                                    currency: 'ISK',
                                    maximumFractionDigits: 0
                                }
                            }),
                            sort: (data) => data.price_compressed ?? 0,
                            filter: (data) => data.price_compressed ?? 0,
                        }
                    },
                    {
                        data: {
                            display: (data) => moment(data.timestamp).utc().format('YYYY-MM-DD HH:mm:ss'),
                            sort: (data) => moment(data.timestamp).unix(),
                            filter: (data) => data.timestamp,
                        }
                    },
                ],
            });
        };

        fetchGet({
            url: aaBeltRadarSettings.url.surveyData,
        })
        .then((data) => {
            const snapshots = Array.isArray(data)
                ? data
                : (Array.isArray(data?.entries) ? data.entries : []);

            if (snapshots.length > 0) {
                tablesContainer.innerHTML = '';

                snapshots.forEach((snapshot, index) => {
                    const snapshotEntries = Array.isArray(snapshot.entries) ? snapshot.entries : [];

                    const headingFragment = headingTemplate.content.cloneNode(true);
                    const headingElement = headingFragment.querySelector('.ore-survey-heading');
                    headingElement.innerHTML = `Snapshot ${index + 1}: ${moment(snapshot.timestamp).utc().format('YYYY-MM-DD HH:mm:ss')} ${snapshot.delete_html}`;
                    tablesContainer.appendChild(headingFragment);

                    const tableFragment = tableTemplate.content.cloneNode(true);
                    const tableElement = tableFragment.querySelector('.ore-survey-table');
                    tableElement.id = `ore-survey-table-${index}`;
                    tablesContainer.appendChild(tableFragment);

                    createSurveyDataTable(tableElement, snapshotEntries);
                    _bootstrapTooltip();
                });
            }
        })
        .catch((error) => {
            console.error('Error fetching Ore Survey data:', error);
        });

        /* Modals */
        const modalRequestDeleteSnapshot = $('#beltradar-accept-delete-snapshot');

        /**
        * Table :: Snapshots :: Delete Button Click Handler
        * Open Delete Snapshot Modal
        * On Confirmation send a request to the API Endpoint, reload the Snapshots DataTable, close the modal
        * and reopen the previous Snapshots Modal
        */
        modalRequestDeleteSnapshot.on('show.bs.modal', (event) => {
            const button = $(event.relatedTarget);
            const url = button.data('action');
            const form = modalRequestDeleteSnapshot.find('form');
            const csrfMiddlewareToken = form.find('input[name="csrfmiddlewaretoken"]').val();

            modalRequestDeleteSnapshot.find('#modal-button-confirm-accept-request').on('click', () => {
                fetchPost({
                    url: url,
                    csrfToken: csrfMiddlewareToken,
                    payload: {}
                })
                .then((data) => {
                    if (data.success === true) {
                        modalRequestDeleteSnapshot.modal('hide');
                        //_reloadSnapshotsDataTable();
                    }
                })
                .catch((error) => {
                    console.error(`Error posting delete request: ${error.message}`);
                });
            });
        })
        .on('hide.bs.modal', () => {
            modalRequestDeleteSnapshot.find('#modal-button-confirm-accept-request').unbind('click');
        });
    });
</script>
