define(['bootstrap'], function (bootstrap) {
    const StatusManager = {
        getstatus: function () {
            $.ajax({
                url: $('#statusURL').val(),
                method: 'GET',
                dataType: 'json',
                success: function (statusResponse) {
                    $('#statusInfo .status').text(`${statusResponse.status.name} (${statusResponse.status.value})`);
                    $('#statusInfo .message').text(statusResponse.message);
                    $('#progressBar')
                        .css('width', `${(statusResponse.completed / statusResponse.total) * 100}% `)
                        .text(`${statusResponse.completed} / ${statusResponse.total}`);

                    if (statusResponse.status.value === 1) { // Status.IN_PROGRESS
                        $('#startUploadBtn').prop('disabled', true);
                        setTimeout(() => {
                            StatusManager.getstatus();
                        }, 1000); // Poll every second
                    } else if (statusResponse.status.value === 2 || statusResponse.status.value === 3) { // FAILED || FINISHED
                        $('#startUploadBtn').prop('disabled', false);
                    }
                },
                error: function () {
                    alert('An error occurred while checking upload status. Please try again.');
                }
            });
        },

        handleUpload: function () {

            var button = $(this);
            button.prop('disabled', true);

            $.ajax({
                url: button.data('url'),
                method: 'POST',
                success: () => {
                    StatusManager.getstatus();
                },
                error: function () {
                    alert('An error occurred while starting the upload. Please try again.');
                }
            });
        },

        checkInitialStatus: function () {
            if ($('#initialStatusUpload').length > 0) {
                const initialStatusUpload = $('#initialStatusUpload').val();
                if (initialStatusUpload == '1') { // Status.IN_PROGRESS
                    StatusManager.getstatus();
                }
            }
            if ($('#initialStatusProof').length > 0) {
                const initialStatusProof = $('#initialStatusProof').val();
                const initialStatusPublish = $('#initialStatusPublish').val();
                if (initialStatusProof === 'QUEUED' || initialStatusProof === 'RUNNING') {
                    StatusManager.getPublishStatus(true);
                } else if (initialStatusPublish === 'QUEUED' || initialStatusPublish === 'RUNNING') {
                    StatusManager.getPublishStatus(false);
                }
            }
        },

        getPublishStatus: function (dryrun) {
            $.ajax({
                url: $('#statusURL').val(),
                data: { dry_run: dryrun },
                method: 'GET',
                dataType: 'json',
                success: function (statusResponse) {
                    const status = statusResponse[dryrun ? 'dryrun' : 'publish'];
                    $('#statusInfo .status').text(status.status.name);
                    $('#statusInfo .message').text(status.message);
                    $('#progressBar')
                        .css('width', `${status.progress}% `)
                        .text(`${status.progress} % `);
                    if (status.status.name === 'FINISHED' || status.status.name === 'FAILED') {
                        $('.start_publication[data-dryrun="' + dryrun + '"]')
                            .prop('disabled', false)
                            .removeClass('active');
                    } else {
                        $('.start_publication[data-dryrun="' + dryrun + '"]').prop('disabled', true);
                        setTimeout(() => {
                            StatusManager.getPublishStatus(dryrun);
                        }, 1000); // Poll every second
                    }
                },
                error: function () {
                    alert('An error occurred while checking upload status. Please try again.');
                }
            });
        },

        handlePublication: function () {
            var button = $(this);
            button.prop('disabled', true);
            button.addClass('active');
            var dryrun = button.data('dryrun');

            $.ajax({
                url: button.data('url'),
                method: 'POST',
                success: () => {
                    setTimeout(() => {
                        StatusManager.getPublishStatus(dryrun);
                    }, 1000);
                },
                error: function () {
                    alert('An error occurred while starting the upload. Please try again.');
                }
            });
        },

        init: function () {
            // upload
            $(document).on('click', '#startUploadBtn', this.handleUpload);
            $(document).on('shown.bs.modal', '#genericModalContainer', this.checkInitialStatus);
            // publish
            $(document).on('click', '.start_publication', this.handlePublication);

        }
    };

    return StatusManager;
});