define(['jquery', 'cla_select2'], function($){
    return function() {

        // Code to help with tabs
        $('#mailTabs a').click(function (e) {
            e.preventDefault();
            $(this).tab('show');
        });

        var url = document.location.toString();
        if (url.match('#')) {
            $('.nav-item a[href="#' + url.split('#')[1] + '"]').tab('show');
        }

        // Change hash for page-reload
        $('#mailTabs .nav-link').on('shown.bs.tab', function (e) {
            window.location.hash = e.target.hash;
        });

        var $fields = $('.js-mail-config-field');
        var $driverPicker = $('#mail_send_driver');

        $fields.find('input:disabled').data('originally-disabled', true);

        var updateDriverUI = function (selectedDriver) {
            $fields.addClass('d-none');
            $fields.find('input').prop('disabled', true);

            var $activeSection = $('.js-mail-driver-' + selectedDriver);

            $activeSection.removeClass('d-none');

            $activeSection.find('input').filter(function () {
                return !$(this).data('originally-disabled');
            }).prop('disabled', false);

            $('.js-driver-desc').addClass('d-none');
            $('#driver_desc_' + selectedDriver).removeClass('d-none');
        };

        $driverPicker.select2();

        updateDriverUI($driverPicker.val());

        $driverPicker.on('change', function () {
            updateDriverUI($(this).val());
        });

        // Code to test driver connection params via REST
        $('#test_connection').on('click', function(evt) {
            evt.preventDefault();

            var driver = $('#mail_send_driver').val();
            var post_data = {
                driver: driver,
                params: {}
            };

            // Extract the fields for the current driver
            $('.js-mail-driver-' + driver).find('input').each(function() {
                var name = '';
                var regex = /\|(.*)]/gm;
                while ((matches = regex.exec($(this).prop('name'))) !== null) {
                    // This is necessary to avoid infinite loops with zero-width matches
                    if (matches.index === regex.lastIndex) {
                        regex.lastIndex++;
                    }

                    matches.forEach(function(match, groupIndex) {
                        name = match;
                    });
                }
                if ($(this).prop('type') === 'radio')
                {
                    // Only use the selected option, not all of them
                    if ($(this).prop('checked'))
                        post_data.params[name] = $(this).val();
                } else
                {
                    post_data.params[name] = $(this).val();
                }
            });

            $.post({
                method: 'POST',
                url: '/api/sysadmin/v1/mail/test_connection',
                data: post_data,
                success: function(data, type, xhr) {
                    // This test is for information only so just report the result
                    if ((typeof data.result === 'boolean') && (data.result))
                    {
                        cla.showMessage(lmsg('panels.sysadmin.mail.config.test_success'), '', false);
                    } else
                    {
                        if ((typeof data.testOccurred === 'boolean') && (data.testOccurred))
                            cla.showMessage(lmsg('panels.sysadmin.mail.config.test_fail'), data.errorMessage, true);
                        else
                            cla.showMessage(lmsg('panels.sysadmin.mail.config.test_not_run'), data.errorMessage, 'info');
                    }
                },
                error: function(xhr, type, message) {
                    cla.showMessage(lmsg('common.error'), lmsg('panels.sysadmin.mail.config.test_error'), true);
                }
            });
        });
    };
});
