{% load i18n %}
{% load evelinks %}
{% load humanize %}
<div class="card card-body mt-2 rounded">
    <span class="mb-2 mt-3 text-muted ore-survey-heading" id="ore-survey-heading"></span>
    <!-- Ore Survey Table -->
    <div class="table-responsive mb-3">
        <table class="table table-striped table-hover w-100" id="beltradar-session-entry-table">
            <thead>
                <tr>
                    <th class="w-auto"></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>
</div>

<script>
    $(document).ready(function() {
        const BeltRadarSessionEntryTable = $('#beltradar-session-entry-table');

        fetchGet({
            url: aaBeltRadarSettings.url.surveySessionEntries,
        })
        .then((data) => {
            if (data) {
                /**
                * DataTable for Belt Radar Sessions
                * @type {*|jQuery}
                */
                const BeltRadarSessionsDataTable = new DataTable(BeltRadarSessionEntryTable, {
                    data: data.entries,
                    language: aaBeltRadarSettings.dataTables.language,
                    layout: aaBeltRadarSettings.dataTables.layout,
                    ordering: aaBeltRadarSettings.dataTables.ordering,
                    columnControl: aaBeltRadarSettings.dataTables.columnControl,
                    order: [[4, '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,
                            }
                        },
                    ],
                    initComplete: function() {
                        $('#ore-survey-heading').html(`Last Snapshot - ${moment(data.timestamp).utc().format('YYYY-MM-DD HH:mm:ss')} - ${data.delete_html}`);
                        _bootstrapTooltip();
                    },
                    drawCallback: function () {
                        _bootstrapTooltip();
                    },
                });
            };
        })
        .catch((error) => {
            console.error('Error fetching Ore Survey data:', error);
        });

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

        /**
        * View :: Reload Survey Snapshot DataTable
        * On Confirmation send a request to the API Endpoint, reload the Survey Snapshot DataTable, close the modal
        * @param {string} url - The API Endpoint URL to send the delete request to returns {Promise}
        * @returns {Promise} - A Promise that resolves when the API request is complete
        */
        const _reloadSurveySnapshotDataTable = (tableData) => {
            const dt = BeltRadarSessionEntryTable.DataTable();
            dt.clear().rows.add(tableData.entries).draw();
            $('#ore-survey-heading').html(`Last Snapshot - ${moment(tableData.timestamp).utc().format('YYYY-MM-DD HH:mm:ss')} - ${tableData.delete_html}`);
            BeltRadarSessionEntryTable.addClass('table-updated-highlight');
            setTimeout(() => {
                BeltRadarSessionEntryTable.removeClass('table-updated-highlight');
            }, 2000);
        };

        /**
        * 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) {
                        fetchGet({
                            url: aaBeltRadarSettings.url.surveySessionEntries,
                        })
                        .then((newData) => {
                            _reloadSurveySnapshotDataTable(newData);
                            modalRequestDeleteSnapshot.modal('hide');
                        })
                        .catch((error) => {
                            console.error('Error fetching Survey Snapshot DataTable:', error);
                        });
                    }
                })
                .catch((error) => {
                    console.error(`Error posting delete request: ${error.message}`);
                });
            });
        })
        .on('hide.bs.modal', () => {
            modalRequestDeleteSnapshot.find('#modal-button-confirm-accept-request').unbind('click');
        });
    });
</script>
