$(document).ready(function() {

    var token = $('body').data('token');

    if ($('.js-galeriapage-price-unity').length > 0) {
        $('.js-galeriapage-price-unity').each(function() {
            setFormatValue($(this));
        });
    }

    $('#galeriapagePriceContainer').on('change', '.js-galeriapage-price-unity', function(){
        $(this).closest('.js-galeriapage-price').find('.js-galeriapage-price-value').val('').focus();
        setFormatValue($(this));
    });

    $('.js-status-api').on('click', function(e){
        e.preventDefault();
        var $this = $(this),
            $environment  = $('select[name="galeriapage_environment"]').val();
        $.ajax({
            type: 'GET',
            url: 'index.php?route=module/galeriapage/settings/statusApi&token=' + token + '&galeriapage_environment=' + $environment,
            dataType: 'json',
            beforeSend: function(){
                $('.js-status-api-result > *').remove();
                $this.addClass('btn-loading');
            },
            complete: function(){
                $this.removeClass('btn-loading');
            },
            success: function(data) {
                if (data.sucess) {
                    $('.js-status-api-result').append('<span class="top-margin-small text-medium text-success visible-block">Status: online</span>');
                } else {
                    $('.js-status-api-result').append('<span class="top-margin-small text-medium text-error visible-block">Status: offline</span>');
                }
            }
        });

    });

    $('.js-auth-api').on('click', function(e){
        e.preventDefault();
        var $this = $(this),
            $email        = $('input[name="galeriapage_email"]').val(),
            $pass         = $('input[name="galeriapage_password"]').val(),
            $environment  = $('select[name="galeriapage_environment"]').val();
        $.ajax({
            type: 'GET',
            url: 'index.php?route=module/galeriapage/settings/authApi&token=' + token + '&galeriapage_email=' + $email + '&galeriapage_password=' + $pass + '&galeriapage_environment=' + $environment,
            dataType: 'json',
            beforeSend: function(){
                $('.js-auth-api-result > *').remove();
                $this.addClass('btn-loading');
            },
            complete: function(){
                $this.removeClass('btn-loading');
            },
            success: function(data) {
                if (data.status) {
                    $('.js-auth-api-result').append('<span class="top-margin-small text-medium text-success visible-block">OK</span>');
                } else {
                    $('.js-auth-api-result').append('<span class="top-margin-small text-medium text-error visible-block">Email ou senha inválido</span>');
                }
            }
        });

    });

});

function setFormatValue(fieldEntryUnity) {
    var
        galeriapagePriceTp = $('#galeriapagePriceContainer').data('galeriapage-price-tp'),
        fieldEntryValue = fieldEntryUnity.closest('.js-galeriapage-price').find('.js-galeriapage-price-value'),
        fieldLabelValue = fieldEntryValue.closest('.js-field').find('.field-label');

    if (fieldEntryUnity.val() == galeriapagePriceTp.Tp_ValorFixo) {
        fieldEntryValue.mask('000.000.000.000.000.00', { reverse: true });
        fieldLabelValue.text('Valor (R$)');
    } else {
        fieldEntryValue.mask('990.0', { reverse: true });
        fieldLabelValue.text('Valor (%)');
    }
}

function initDocument() {

    const ERROR = document.querySelector('.js-error');
    if (ERROR) {
        const TAB = ERROR.closest('[data-tab]').dataset.tab;
        document.querySelector(`[data-tab-control=${TAB}]`).click();
    }

    var
        container = document.getElementById('galeriapagePriceContainer'),
        btnPriceAdd = document.getElementById('galeriapagePriceAdd');

    if (container.querySelectorAll('.js-galeriapage-price-remove').length > 0) {
        var btnPriceRemove = container.querySelectorAll('.js-galeriapage-price-remove');
        for (var i = 0; i < btnPriceRemove.length; i++) {
            btnPriceRemove[i].onclick = priceRemove;
        }
    }

    btnPriceAdd.onclick = priceAdd.bind(btnPriceAdd, container);
}

function priceRemove() {
    var child = closestElement.call(this, 'js-galeriapage-price');
    child.parentNode.removeChild(child);
    document.getElementById('galeriapagePriceAdd').removeAttribute('disabled');
}

function priceAdd(container) {
    var
        priceLength = container.querySelectorAll('.js-galeriapage-price').length,
        type = JSON.parse(container.getAttribute('data-galeriapage-price-type')),
        unity = JSON.parse(container.getAttribute('data-galeriapage-price-unity')),
        typeOption = '',
        unityOption = '',
        div = document.createElement('div');

    if (priceLength == 4){
        document.getElementById('galeriapagePriceAdd').setAttribute('disabled', '');
    }

    for (var i = 0; i < type.length; i++) {
        typeOption += '<option value="' + type[i].value + '">' + type[i].description + '</option>';
    }
    for (var i = 0; i < unity.length; i++) {
        unityOption += '<option value="' + unity[i].value + '">' + unity[i].description + '</option>';
    }

    var
        html = '<div class="field-group-join">' +
            '<label class="field field-medium js-field">' +
            '<span class="field-label">Tipo</span>' +
            '<select class="field-entry" name="galeriapage_price[' + priceLength + '][typeadjustment]">' +
            typeOption +
            '</select>' +
            '</label>' +
            '<label class="field field-medium js-field">' +
            '<span class="field-label">Unidade</span>' +
            '<select class="field-entry js-galeriapage-price-unity" name="galeriapage_price[' + priceLength + '][type_price_adjustment]">' +
            unityOption +
            '</select>' +
            '</label>' +
            '<label class="field field-medium js-field">' +
            '<span class="field-label">Valor (%)</span>' +
            '<div class="field-entry-group">' +
            '<input class="field-entry js-galeriapage-price-value" type="text" name="galeriapage_price[' + priceLength + '][price_adjustment]" value="" size="4">' +
            '<button type="button" class="btn-default btn-medium-square btn-error js-galeriapage-price-remove">' +
            '<i class="fas fa-times"></i>' +
            '</button>' +
            '</div>' +
            '</label>' +
            '</div>';

    div.setAttribute('class', 'background-white shadow-small adm-focus-within padding-large bottom-margin-small galeriapage-price js-galeriapage-price');
    div.insertAdjacentHTML('afterbegin', html);
    div.querySelector('.js-galeriapage-price-remove').onclick = priceRemove;

    setFormatValue($(div).find('.js-galeriapage-price-unity'));

    container.insertBefore(div, container.firstChild)

    div.querySelector('.js-galeriapage-price-value').focus();
}


document.addEventListener('DOMContentLoaded', initDocument);