import $ from 'jquery';

(function($){

    const AdminGateway = {

        init: () => {

			AdminGateway.topNav();
		    CembraPayAdminConditionalSettings.init();
            APIConnectionStatus.init();

            setInterval(function() {
                $('.wcml-pointer-block').remove();
            }, 1000);
		
		},
		topNav: () => {

			const target   = jQuery('#mainform h2');
			const sections = jQuery('#mainform h3');
			let markup   = '<ul style="width: 100%;" class="subsubsub cembrapay-top-nav">';
		
			sections.each(function(i, section){

				if( jQuery(this).text() && jQuery(this).attr('id') != 'woocommerce_cembrapay_localization_separator' ) {
                    let id = jQuery(this).attr('id');
					markup += '<li class="' + id + '"><a href="#' + id + '">' + jQuery(this).text() + '</a> <span class="sep">|</span></li>';
				}

			});
		
			markup += '</ul>';
		
			target.before( markup );
		
			jQuery('body').on('click', '.cembrapay-top-nav a', function(evt) {
				evt.preventDefault();
		
				jQuery('html, body').animate({
					scrollTop: jQuery( jQuery(this).attr('href') ).offset().top - 100
				}, 1500);
		
			})
		
		}

    }
    
    const CembraPayAdminConditionalSettings = {

        init: () => {
            CembraPayAdminConditionalSettings.checkoutAuthorization();
            CembraPayAdminConditionalSettings.orderPrefix();
            CembraPayAdminConditionalSettings.orderIdSource();
            CembraPayAdminConditionalSettings.salutation();
            CembraPayAdminConditionalSettings.birthdate();
            CembraPayAdminConditionalSettings.companyRegistration();
            CembraPayAdminConditionalSettings.installments();
            CembraPayAdminConditionalSettings.invoiceType();
            CembraPayAdminConditionalSettings.logs();
        },
        checkoutAuthorization: () => {

            const enableCheckoutAuthorization = jQuery('#woocommerce_cembrapay_auth_type');
            const salutationBlock        = jQuery('#woocommerce_cembrapay_use_salutation_field').parents('table');
            const salutationTitle        = jQuery('#woocommerce_cembrapay_salutation_settings');
            const salutationSeparator    = jQuery('#salutation_separator');
            const salutationNavItem      = jQuery('.cembrapay-top-nav .woocommerce_cembrapay_salutation_settings');
            const birthdateBlock     = jQuery('#woocommerce_cembrapay_use_birthdate_field').parents('table');
            const birthdateTitle     = jQuery('#woocommerce_cembrapay_birthdate_settings');
            const birthdateSeparator = jQuery('#birthdate_separator');
            const birthdateNavItem   = jQuery('.cembrapay-top-nav .woocommerce_cembrapay_birthdate_settings');

            if( 1 == parseInt( enableCheckoutAuthorization.val() ) ) {
                salutationBlock.hide();
                salutationTitle.hide();
                salutationSeparator.hide();
                salutationNavItem.hide();
                birthdateBlock.hide();
                birthdateTitle.hide();
                birthdateSeparator.hide();
                birthdateNavItem.hide();
            }

            if( 2 == parseInt( enableCheckoutAuthorization.val() ) ) {
                salutationBlock.show();
                salutationTitle.show();
                salutationSeparator.show();
                salutationNavItem.show();
                birthdateBlock.show();
                birthdateTitle.show();
                birthdateSeparator.show();
                birthdateNavItem.show();
            }

            enableCheckoutAuthorization.on('change', function(evt) {
                CembraPayAdminConditionalSettings.checkoutAuthorization();
            });

        },
        orderPrefix: () => {

            // Order prefix field

            const enableOrderIdPrefix = jQuery('#woocommerce_cembrapay_use_order_id_prefix');
            const orderIdPrefix 	  = jQuery('#woocommerce_cembrapay_order_id_prefix');
            const orderIdPrefixParent = orderIdPrefix.parents('tr');
        
            if( enableOrderIdPrefix.val() < 1 ) {
                orderIdPrefixParent.hide();
            }
        
            enableOrderIdPrefix.on('change', function(evt) {
                parseInt( jQuery(this).val() ) > 0 ? orderIdPrefixParent.show() : orderIdPrefixParent.hide();
            });

        },
        orderIdSource: () => {

            // Order ID source field

            const orderIdSource  = jQuery('#woocommerce_cembrapay_order_id_source');
            const orderIdMetaKey = jQuery('#woocommerce_cembrapay_order_id_meta_key');
            const orderIdMetaKeyParent = orderIdMetaKey.parents('tr');
        
            if( 1 == orderIdSource.val() ) {
                orderIdMetaKeyParent.hide();
            }
        
            orderIdSource.on('change', function(evt) {
                2 == parseInt( jQuery(this).val() ) ? orderIdMetaKeyParent.show() : orderIdMetaKeyParent.hide();
            });

        },
        salutation: () => {

            // Salutation field

            const enableSalutationField   = jQuery('#woocommerce_cembrapay_use_salutation_field');
            const salutationFieldFirstRow = enableSalutationField.parents('tr');
            const salutationFieldRows     = enableSalutationField.parents('table').find('tr');

            if( ! parseInt( enableSalutationField.val() ) ) {
                salutationFieldRows.hide();
                salutationFieldFirstRow.show();
            }

            enableSalutationField.on('change', function(evt) {

                if( ! parseInt( jQuery(this).val() ) ) {
                    salutationFieldRows.hide();
                    salutationFieldFirstRow.show();
                }

            });

        },
        birthdate: () => {

            // Birthdate field

            const enableBirthdateField 		= jQuery('#woocommerce_cembrapay_use_birthdate_field');
            const birthdateFieldFirstRow 		= enableBirthdateField.parents('tr');
            const birthdateFieldRows 			= enableBirthdateField.parents('table').find('tr');
            const birthdateType				= jQuery('#woocommerce_cembrapay_birthdate_field_type');
            const birthdateTypeSeparateFields = jQuery('#woocommerce_cembrapay_birthdate_field_day_label, #woocommerce_cembrapay_birthdate_field_month_label, #woocommerce_cembrapay_birthdate_field_year_label').parents('tr');

            if( ! parseInt( enableBirthdateField.val() ) ) {

                birthdateFieldRows.hide();
                birthdateFieldFirstRow.show();

            } else {

                switch( parseInt( birthdateType.val() ) ) {
                    case 1:
                        birthdateTypeSeparateFields.show();
                    break;
                    case 2:
                        birthdateTypeSeparateFields.hide();
                    break;
                }

            }

            enableBirthdateField.on('change', function(evt) {

                if( ! parseInt( jQuery(this).val() ) ) {

                    birthdateFieldRows.hide();
                    birthdateFieldFirstRow.show();

                } else {

                    birthdateFieldRows.show();

                    switch( parseInt( birthdateType.val() ) ) {
                        case 1:
                            birthdateTypeSeparateFields.show();
                        break;
                        case 2:
                            birthdateTypeSeparateFields.hide();
                        break;
                    }

                }

            });

            birthdateType.on('change', function(evt) {

                switch( parseInt( jQuery(this).val() ) ) {
                    case 1:
                        birthdateTypeSeparateFields.show();
                    break;
                    case 2:
                        birthdateTypeSeparateFields.hide();
                    break;
                }

            });

        },
        companyRegistration: () => {

            // Company registration field

            const enableCompanyRegField = jQuery('#woocommerce_cembrapay_use_company_reg_field');
            const companyRegFirstRow    = enableCompanyRegField.parents('tr');
            const companyRegFieldRows   = enableCompanyRegField.parents('table').find('tr');

            if( ! parseInt( enableCompanyRegField.val() ) ) {
                companyRegFieldRows.hide();
                companyRegFirstRow.show();
            }

            enableCompanyRegField.on('change', function(evt) {

                if( ! parseInt( jQuery(this).val() ) ) {
                    companyRegFieldRows.hide();
                    companyRegFirstRow.show();
                } else {
                    companyRegFieldRows.show();
                }

            });

        },
        installments: () => {

            //Installments fields

            const enableInstallmentsField = jQuery('#woocommerce_cembrapay_use_installments');
            const installmentsFirstRow    = enableInstallmentsField.parents('tr');
            const installmentsFieldRows   = enableInstallmentsField.parents('table').find('tr');

            CembraPayAdminConditionalSettings.toggleInstallments();

            if( ! parseInt( enableInstallmentsField.val() ) ) {
                installmentsFieldRows.hide();
                installmentsFirstRow.show();
            }

            enableInstallmentsField.on('change', function(evt) {

                if( ! parseInt( enableInstallmentsField.val() ) ) {
                    installmentsFieldRows.hide();
                    installmentsFirstRow.show();
                } else {
                    installmentsFieldRows.show();
                    CembraPayAdminConditionalSettings.toggleInstallments();
                }

            });

        },
        toggleInstallments: () => {

            for( let installmentType of [ 'cembrapay_invoice', 'installments_full', 'installments_3', 'installments_6', 'installments_4', 'installments_12', 'installments_24', 'installments_36', 'installments_48' ] ) {

                const installmentToggle   = jQuery( '#woocommerce_cembrapay_use_' + installmentType );
                const installmentFor      = jQuery('#woocommerce_cembrapay_' + installmentType + '_for').parents('tr');
                const installmentTemplate = jQuery('#woocommerce_cembrapay_' + installmentType + '_template').parents('tr');

                if( installmentToggle.is(':checked') ) {
                    installmentFor.show();
                    installmentTemplate.show();
                } else {
                    installmentFor.hide();
                    installmentTemplate.hide();
                }

                installmentToggle.on('change', function(evt) {
                    if( jQuery(this).is(':checked') ) {
                        installmentFor.show();
                        installmentTemplate.show();
                    } else {
                        installmentFor.hide();
                        installmentTemplate.hide();
                    }
                });

            }

        },
        invoiceType: () => {

            //Invoice type field

            const enableInvoiceTypeField = jQuery('#woocommerce_cembrapay_use_invoice_type');
            const invoiceTypeFirstRow    = enableInvoiceTypeField.parents('tr');
            const invoiceTypeFieldRows   = enableInvoiceTypeField.parents('table').find('tr');

            if( ! parseInt( enableInvoiceTypeField.val() ) ) {
                invoiceTypeFieldRows.hide();
                invoiceTypeFirstRow.show();
            }

            enableInvoiceTypeField.on('change', function(evt) {

                if( ! parseInt( jQuery(this).val() ) ) {
                    invoiceTypeFieldRows.hide();
                    invoiceTypeFirstRow.show();
                } else {
                    invoiceTypeFieldRows.show();
                }

            });

        },
        logs: () => {

            const enableLogsField = jQuery('#woocommerce_cembrapay_logs_enable');
            const deleteLogs      = jQuery('#woocommerce_cembrapay_logs_deletion');
            const logsLink		= jQuery('#woocommerce_cembrapay_logs_separator');

            if( ! parseInt( enableLogsField.val() ) ) {
                logsLink.hide();
            }

            enableLogsField.on('change', function(evt) {

                if( ! parseInt( jQuery(this).val() ) ) {
                    deleteLogs.parents('tr').hide();
                    logsLink.hide();
                } else {
                    deleteLogs.parents('tr').show();
                    logsLink.show();
                }

            });

        }

    }

    const APIConnectionStatus = {
        init: () => {
            const hasConnectionStatus = jQuery('#woocommerce_cembrapay_connection_status');
            if( hasConnectionStatus.length ) {
                APIConnectionStatus.check();
            }
        },
        check: () => {

            const connectionStatusContainer = jQuery('#woocommerce_cembrapay_connection_status').parents('td');
            connectionStatusContainer.html('<div class="spinner is-active" style="float: none;"></div>');

            jQuery.ajax('/wp-json/cembrapay/v1/get-connection-status', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                },
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', cembrapayAdmin.nonce)
                },
                dataType: 'json',
                success: function (response) {
                    
                    if( 1 === response.status ) {
                        connectionStatusContainer.html('<span style="color: green; font-weight: bold;">' + response.message + '</span>');
                    }

                    if( 0 === response.status ) {
                        connectionStatusContainer.html('<span style="color: red; font-weight: bold;">' + response.message + '</span>');
                    }
                    
                }
            });

        }
    }

    jQuery(() => {
        AdminGateway.init();
    });

})(jQuery);