import $ from 'jquery';
import icon from './elements/icon';
import langs from './elements/languages';
import languageRow from './elements/language-row';
import fields from './elements/fields';
import modal from './elements/modal';
import {preloader, preloaderCenter} from './elements/preloaders';

(function($){

    let state = {
        icon: icon,
        languages: langs,
        fields: fields,
        activeFieldId: '',
        activeFieldType: '',
        saveButton: `
        <button 
            id="save-translations" 
            type="button" 
            class="button button-primary"
        >
            ${cembrapayTranslations.strings.saveTranslations}
        </button>`
    }

    const AdminTranslations = {

        init: () => {
            
            modal.init();

            for (let field of state.fields) {
                jQuery(`#woocommerce_cembrapay_${field.id}`).after(`
                    <a 
                        class="cembrapay-open-translations" 
                        title="Field translations" 
                        data-field="${field.id}" 
                        data-type="${field.type}"
                    >
                        ${state.icon}
                    </a>
                    <div class="spinner"></div>
                `);
            }

            const removeTranslationControls = setInterval(() => {
                if( jQuery('.translation_controls').length ) {
                    jQuery('.translation_controls').remove();
                    clearInterval(removeTranslationControls);
                }
            }, 1000);

        },

        modal: {

            data: {

                loadTranslations: field => {

                    state.activeFieldId   = field.data('field');
                    state.activeFieldType = field.data('type');

                    modal.content.html(preloaderCenter);

                    const theField = state.fields.filter( field => field.id === state.activeFieldId )[0];
                    
                    modal.title.html(`${cembrapayTranslations.strings.translationsFor} ${theField && theField.label ? theField.label : field.data('field')}`);

                    jQuery.ajax({
                        url: cembrapayTranslations.ajaxUrl,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'get_field_translations',
                            security: cembrapayTranslations.nonceGet,
                            field: field.data('field')
                        },
                        success: function(response) {

                            jQuery('.spinner-main').remove();

                            if( response.success ) {

                                for (let lang in response.data ) {

                                    modal.content.append( languageRow({id: state.activeFieldId, type: state.activeFieldType, value: response.data[lang], lang: lang}) );

                                }

                                if( ! jQuery('#save-translations').length ) {
                                    modal.footer.append( state.saveButton );
                                }

                            }

                            modal.content.prepend(`
                                <button 
                                    id="add-translation" 
                                    type="button" 
                                    class="button button-primary" 
                                    data-fieldtype="${state.activeFieldType}"
                                >
                                ${cembrapayTranslations.strings.addTranslation}
                                </button>
                            `);


                        },
                        error: function(xhr, status, error) {
                            console.log(xhr, status, error);
                            modal.errors.html(`<p>${error}</p>`);
                        }
                    });

                },
                addTranslation: () => {

                    modal.content.append( languageRow({id: state.activeFieldId, type: state.activeFieldType}) );

                    if( ! jQuery('#save-translations').length ) {
                        modal.footer.append( state.saveButton );
                    }

                },
                saveTranslations: () => {

                    if( ! modal.footer.find('.spinner').length > 0 ) {
                        modal.footer.append( preloader );
                    }

                    let translations = [];

                    jQuery('.language-row').each(function(idx, langRow) {
                        translations.push({
                            lang: jQuery(langRow).find('#language').val(),
                            value: jQuery(langRow).find(`#${state.activeFieldId}`).val()
                        });
                    });

                    if( ! translations.length ) {
                        modal.errors.html(`<p>${cembrapayTranslations.strings.translationsMandatory}</p>`);
                        jQuery('.spinner-main').remove();
                        return false;
                    }

                    jQuery.ajax({
                        url: cembrapayTranslations.ajaxUrl,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            action: 'update_field_translations',
                            security: cembrapayTranslations.nonceUpdate,
                            field: state.activeFieldId,
                            translations: translations
                        },
                        success: function(response) {

                            jQuery('.spinner-main').remove();
                            
                            if( ! jQuery('#translations-saved').length ) {
                                jQuery('#save-translations').after(`<span id="translations-saved" style="color: green; margin-left: 10px;">${ cembrapayTranslations.strings.saved }</span>`);

                                setTimeout(() => {
                                    jQuery('#translations-saved').remove();
                                }, 2000);
                            }

                        },
                        error: function(xhr, status, error) {
                            console.log(xhr, status, error);
                            jQuery('.spinner-main').remove();
                            modal.errors.html(`<p>${error}</p>`);
                        }
                    });

                },
                deleteTranslation: field => {
                    field.parents('.language-row').remove();
                }

            },

        }

    }

    jQuery(() => {

        AdminTranslations.init();

        jQuery('body').on('click', '.cembrapay-open-translations', function(evt) {
            evt.preventDefault();
            modal.open( jQuery(this) );
            modal.content.css('height', 'auto');
            AdminTranslations.modal.data.loadTranslations( jQuery(this) );
        });

        jQuery('body').on('click', '.cembrapay-modal #close, .cembrapay-modal #bg', function(evt) {
            evt.preventDefault();
            modal.close();
        });

        jQuery('body').on('click', '#add-translation', function(evt) {
            evt.preventDefault();
            AdminTranslations.modal.data.addTranslation();
        });

        jQuery('body').on('click', '#save-translations', function(evt) {
            evt.preventDefault();
            AdminTranslations.modal.data.saveTranslations();
        });

        jQuery('body').on('click', '.language-row .remove', function(evt) {
            evt.preventDefault();
            AdminTranslations.modal.data.deleteTranslation( jQuery(this) );
        });

    });

})(jQuery);