define([
    "jquery",
    "Magento_Ui/js/modal/alert",
    "mage/translate",
    "jquery/ui"
], function ($, alert, $t) {
    "use strict";

    $.widget('mage.testConnection', {
        options: {
            ajaxUrl: '',
            testConnection: '#carriers_orlenpaczka_test_connection',
            partnerId: '#carriers_orlenpaczka_partner_id',
            partnerKey: '#carriers_orlenpaczka_partner_key',
        },
        _create: function () {
            $(this.options.testConnection).click((event) => {
                event.disabled = true;
                event.preventDefault();
                this._ajaxSubmit();
            });
        },

        _ajaxSubmit: function () {
            $.ajax({
                url: this.options.ajaxUrl,
                data: {
                    partnerId: $(this.options.partnerId).val(),
                    partnerKey: $(this.options.partnerKey).val()
                },
                dataType: 'json',
                showLoader: true,
                success: (result) => {
                    alert({
                        title: result.status ? $t('Success') : $t('Error'),
                        content: result.content
                    });
                },
                always: () => {
                    $(this.options.testConnection).prop('disabled', false);
                }
            });
        }
    });

    return $.mage.testConnection;
});
