<?php
/**
 * Maho
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://magento.com)
 * @copyright   Copyright (c) 2022-2024 The OpenMage Contributors (https://openmage.org)
 * @copyright   Copyright (c) 2024 Maho (https://mahocommerce.com)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/** @var Mage_Adminhtml_Block_System_Config_System_Storage_Media_Synchronize $this */
?>

<script type="text/javascript">
//<![CDATA[
    Validation.add('required-synchronize', '<?= Mage::helper('core')->jsQuoteEscape($this->__('Synchronization is required.')) ?>', function(){
        storage = getConnectionName(
            $('system_media_storage_configuration_media_storage').value,
            $('system_media_storage_configuration_media_database').value
        );

        return allowedStorages.include(storage);
    });

    defaultValues   = [];
    defaultValues['system_media_storage_configuration_media_storage']   = $('system_media_storage_configuration_media_storage').value;
    defaultValues['system_media_storage_configuration_media_database']  = $('system_media_storage_configuration_media_database').value;

    allowedStorages = [];
    addAllowedStorage(
        $('system_media_storage_configuration_media_storage').value,
        $('system_media_storage_configuration_media_database').value
    );

    <?php $syncStorageParams = $this->getSyncStorageParams() ?>
    addAllowedStorage(<?= $syncStorageParams['storage_type'] ?>, '<?= $syncStorageParams['connection_name'] ?>');

    function getConnectionName(storageType, connection)
    {
        if (storageType == 0) {
            return storageType;
        } else if (connection != '') {
            return storageType + '_' + connection;
        }

        return '';
    }

    function addAllowedStorage(storageType, connection)
    {
        storage = getConnectionName(storageType, connection);

        if (storage != '' && !allowedStorages.include(storage)) {
            allowedStorages.push(storage);
        }
    }

    function checkButtonState(event) {
        var element = Event.element(event);

        defaultStorage = getConnectionName(
            defaultValues['system_media_storage_configuration_media_storage'],
            defaultValues['system_media_storage_configuration_media_database']
        );

        storage = getConnectionName(
            $('system_media_storage_configuration_media_storage').value,
            $('system_media_storage_configuration_media_database').value
        );

        if (defaultStorage != storage) {
            enableSyncButton();
        } else {
            disableSyncButton();
        }
    }

    function enableStorageSelection() {
        $('system_media_storage_configuration_media_storage').enable('enabled');
        $('system_media_storage_configuration_media_database').enable('enabled');
    }

    function disableStorageSelection() {
        $('system_media_storage_configuration_media_storage').disable('disabled');
        $('system_media_storage_configuration_media_database').disable('disabled');
    }

    function enableSyncButton() {
        Form.Element.enable('synchronize_button');
        $('synchronize_button').removeClassName('disabled');
    }

    function disableSyncButton() {
        Form.Element.disable('synchronize_button');
        $('synchronize_button').addClassName('disabled');
    }

    Event.observe(window, 'load', function(){
        disableStorageSelection();
        disableSyncButton();
        checkStatus();
    });
    $('system_media_storage_configuration_media_storage').observe('change', checkButtonState);
    $('system_media_storage_configuration_media_database').observe('change', checkButtonState);

    function checkStatus() {
        var u = new Ajax.PeriodicalUpdater('', '<?= $this->getAjaxStatusUpdateUrl() ?>', {
            method:     'get',
            frequency:  5,
            loaderArea: false,

            onSuccess: function(transport) {
                var response;

                try {
                    response = transport.responseJSON || transport.responseText.evalJSON(true) || {};
                    if (response.state == '<?= Mage_Core_Model_File_Storage_Flag::STATE_RUNNING ?>'
                        && response.message
                    ) {
                        if ($('sync_span').hasClassName('no-display')) {
                            $('sync_span').removeClassName('no-display');
                            $('sync_message_span').update(response.message);
                        }
                    } else {
                        u.stop();
                        enableStorageSelection();
                        $('sync_span').addClassName('no-display');

                        if (response.state == '<?= Mage_Core_Model_File_Storage_Flag::STATE_NOTIFIED ?>') {
                            if (response.html && response.html != '') {
                                $$('div.notification-global').each(function(e) {
                                    if (!e.hasClassName('notification-global-notice')) {
                                        e.hide();
                                    }
                                });

                                Element.insert($('anchor-content'), {'before': response.html});
                            }

                            if (response.has_errors) {
                                enableSyncButton();
                            } else {
                                addAllowedStorage(
                                    $('system_media_storage_configuration_media_storage').value,
                                    $('system_media_storage_configuration_media_database').value
                                );
                            }
                        }
                    }
                } catch (e) {
                    response = {};
                }
            }
        });
    }

    function synchronize() {
        var advice = Validation.getAdvice('required-synchronize', $('synchronize-validation-input'));
        if (advice) {
            advice.hide();
        }
        params = {
            storage:    $('system_media_storage_configuration_media_storage').value,
            connection: $('system_media_storage_configuration_media_database').value
        }

        new Ajax.Request('<?= $this->getAjaxSyncUrl() ?>', {
            parameters:     params,
            loaderArea:     false,
            asynchronous:   true
        });

        window.setTimeout('checkStatus()', 2011);

        disableStorageSelection();
        disableSyncButton();
    }
//]]>
</script>

<?= $this->getButtonHtml() ?><span class="sync-indicator no-display" id="sync_span"><img alt="Synchronize" style="margin:0 5px" src="<?= $this->getSkinUrl('images/process_spinner.gif') ?>"/><span id="sync_message_span">
<input type="hidden" id="synchronize-validation-input" class="required-synchronize no-display"/>
