/**
 * 2018 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2018 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */
$(document).ready(function() {
    let select_country = $('#input-gateway-delivery-country');
    let select_city = $('#input-gateway-delivery-city');
    let select_terminal = $('#input-gateway-delivery-terminal');
    let btn_shipping_method = $('#js-delivery button[name="confirmDeliveryOption"]');
    let delivery_gateway_content = $('.paysera-delivery-gateway-content');
    let delivery_gateway_warning_content = $('.paysera-delivery-gateway-warning');
    let loading = new Option('Loading...', 0, true, true);
    let url = '/index.php?fc=module&module=payseradelivery&controller=api';
    let default_index = 'default';
    let selected_shipping_method = '';
    let selected_country = 'default';
    let selected_city = 'default';

    if ($('.delivery-options input[type="radio"]:checked').length) {
        selected_shipping_method = $('.delivery-options input[type="radio"]:checked').val().replace(',', '');
    }

    $(document, 'body').on('change', '#js-delivery input', function() {
        let option_container = $(this).parent().parent().parent();
        selected_shipping_method = $(this).val().replace(',', '');
        validate(selected_shipping_method,option_container);
    });

    const validate = (shipping_method_id, option_container) => {
        return $.ajax({
            url,
            data: {
                method: 'validate',
                carrier: shipping_method_id
            }
        }).done(function (validationResponse) {
            validationResponse = JSON.parse(validationResponse);
            selected_country = validationResponse.selected_country;
            selected_city = validationResponse.selected_city;
            btn_shipping_method.prop('disabled', true);

            fetchCountries('country', shipping_method_id);

            if (validationResponse.has_delivery_terminal === 1) {
                if (validationResponse.error) {
                    delivery_gateway_warning_content.show();
                    delivery_gateway_warning_content.html(validationResponse.error);
                    delivery_gateway_content.hide();
                } else {
                    option_container.append(delivery_gateway_content);
                    delivery_gateway_content.show();
                    delivery_gateway_warning_content.hide();
                    delivery_gateway_content.show();
                }
            } else {
                delivery_gateway_content.hide();
                delivery_gateway_warning_content.hide();
                btn_shipping_method.prop('disabled', false);

                option_container.append(delivery_gateway_content);
                delivery_gateway_content.hide();
            }
        });
    }

    select_country.select2();
    select_city.select2();
    select_terminal.select2();

    const fetchCountries = (method, shipping_method_id) => {
        return $.ajax({
            url,
            data: {
                method,
                carrier: selected_shipping_method,
            }
        }).done(function (countries) {
            let arrayCountries = JSON.parse(countries);
            let options = '';

            for (const [country_id, country_name] of Object.entries(arrayCountries)) {
                options += `<option value='${country_id}'>${country_name}</option>`;
            }

            select_country.html(options);

            select_city.parent().parent().hide();
            select_terminal.parent().parent().hide();

            select_country.val(selected_country).trigger('change');
            select_country.val(selected_country).trigger('select2:select');
        });
    }

    if (selected_shipping_method) {
        let option_container = $('.delivery-options input[type="radio"]:checked').parent().parent().parent();
        validate(selected_shipping_method,option_container);
    }

    select_country.on('select2:select', function(el) {
        let country_id = $(this).val();
        let method = 'city';

        if (country_id !== default_index) {
            select_city.empty();
            select_city.append(loading).trigger('change');
            select_city.val(0).trigger('change');
            select_city.parent().parent().show();

            select_terminal.empty();
            select_terminal.parent().parent().hide();

            $.ajax({
                url,
                data: {
                    method,
                    country: country_id,
                    carrier: selected_shipping_method
                }
            }).done(function (cities) {
                cities = JSON.parse(cities);

                let options = `<option value='${default_index}'>${cities.default}</option>`;

                delete cities.default;

                for (var key of Object.keys(cities)) {
                    options += `<option value='${cities[key]}'>${cities[key]}</option>`;
                }

                select_city.html(options);
                select_city
                    .val(getDiacriticFreeSelectionValue(select_city, selected_city))
                    .trigger('select2:select');
            });
        } else {
            select_city.parent().parent().hide();
            select_terminal.parent().parent().hide();
        }
    });

    select_city.on('select2:select', function(el) {
        let country_id = select_country.val();
        let city = $(this).val();
        let method = 'terminal';

        if (country_id !== default_index && city !== default_index) {
            select_terminal.empty();
            select_terminal.append(loading).trigger('change');
            select_terminal.parent().parent().show();

            $.ajax({
                url,
                data: {
                    carrier: selected_shipping_method,
                    country: country_id,
                    city,
                    method
                }
            }).done(function (terminals) {
                terminals = JSON.parse(terminals);

                let options;

                for (const [terminal_id, terminal_name] of Object.entries(terminals)) {
                    options += `<option value='${terminal_id}'>${terminal_name}</option>`;
                }

                select_terminal.html(options);
                select_terminal.val('default').trigger('change');
            });
        } else {
            select_terminal.parent().parent().hide();
            btn_shipping_method.prop('disabled', true);
        }
    })

    select_terminal.on('select2:select', function(el) {
        let country_id = select_country.val();
        let city = select_city.val();
        let terminal = $(this).val();
        let is_disabled = (
            country_id !== default_index
            && city !== default_index
            && terminal !== default_index
        )

        if (terminal !== default_index) {
            $.ajax({
                url,
                data: {
                    method: 'save_terminal',
                    carrier: selected_shipping_method,
                    country: country_id,
                    city,
                    terminal
                }
            })
                .done(function () {
                    btn_shipping_method.prop('disabled', !is_disabled);
                });
        }
    });

    function removeDiacritics(str) {
        return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    }

    function getDiacriticFreeSelectionValue(jquerySelectionElement, selectedValue) {
        if (typeof selectedValue === 'string' && selectedValue !== '') {
            selectedValue = removeDiacritics(selectedValue).toLowerCase();

            jquerySelectionElement.find('option').each(function () {
                const val = $(this).val();

                if (removeDiacritics(val).toLowerCase() === selectedValue) {
                    selectedValue = val;
                    return false;
                }
            });
        } else {
            selectedValue = 'default';
        }

        return selectedValue;
    }
});
