/**
 * Panel generator page scripts
 *
 * @version 1.0.0
 * @since 7.0.0
 */

var generator_required = [];
window.et_panel = window.et_panel || {};
!function($) {
    $(document).ready(function ($) {
        var et_generator = {
            generator_section_child_change: function(_this) {
                if (!_this.prop('checked')) {
                    _this.parents('.opt-section').find('input:not(.input-section)').prop('checked', false);
                } else {
                    _this.parents('.opt-section').find('input:not(.input-section)').prop('checked', true);
                }
            },
            generator_subsection_child_change: function(_this) {
                if (!_this.prop('checked')) {
                    _this.parents('.opt-subsection').find('input:not(.has-subsection)').prop('checked', false);
                } else {
                    _this.parents('.opt-subsection').find('input:not(.has-subsection)').prop('checked', true);
                }
            },
            generator_parent_change: function(_this) {
                if (_this.prop('checked')) {
                    _this.closest('.has-subsection').find('.opt-item').first().find('input').prop('checked', true);
                    _this.closest('.opt-section.has-subsection').find('.opt-item').first().find('input').prop('checked', true);
                }
            },
            generator_remove_file: function(_this) {
                if ( !confirm('Are you sure? ')) return;
                $.ajax({
                    method: "POST",
                    url: ajaxurl,
                    dataType: 'JSON',
                    data: {
                        action: 'et_panel_ajax',
                        type: 'css',
                        action_type: 'et_generator_remover',
                    },
                    success: function (response) {
                        if (response.status == 'success') {
                            $('.css_generator-info').html('');
                            $('.css_generator-info').html(response.response.html).addClass('no-file-generated');
                        } else {
                            alert(response.response.msg);
                        }
                    },
                    error: function () {
                        alert('ajax error');
                    }
                });
            },
            generator_calc: function(_this) {
                et_panel.generator_calc_system_files(_this);
                et_panel.generator_set_counter();
            },
            generator_generate_file: function(_this,e) {
                e.preventDefault();

                var form_data = _this.serializeArray(),
                    modules = '',
                    added_modules = [],
                    popup = $('.et_panel-popup'),
                    spinner = '<div class="et-loader ">\
					<svg class="loader-circular" viewBox="25 25 50 50">\
					<circle class="loader-path" cx="50" cy="50" r="12" fill="none" stroke-width="2" stroke-miterlimit="10"></circle>\
					</svg>\
				</div>';

                $.each(form_data, function (e, t) {
                    if (t.value.includes(',')) {
                        var t_var = t.value.split(',');
                        $.each(t_var, function (i, v) {
                            if (!added_modules.includes(v)) {
                                added_modules.push(v);
                                modules += v + ',';
                            }
                        });
                    } else {
                        modules += t.value + ',';
                    }
                });
                modules = modules.slice(0, -1);

                popup.html(spinner);

                $('body').addClass('et_panel-popup-on');

                $.ajax({
                    method: "POST",
                    url: ajaxurl,
                    dataType: 'JSON',
                    data: {
                        action: 'et_panel_ajax',
                        modules: modules,
                        type: _this.attr('type'),
                        action_type: 'et_generator',
                    },
                    success: function (response) {
                        popup.html('');
                        popup.addClass('loading');
                        popup.prepend('<span class="et_close-popup et-button-cancel et-button"><i class="et-admin-icon et-delete"></i></span>');
                        popup.addClass('panel-popup-import').append(response.response.icon);
                        popup.append(response.response.msg);
                        popup.append(response.response.btn);
                        popup.addClass('active').removeClass('loading');

                        if (response.status == 'success') {
                            $('.css_generator-info').html('');
                            $('.css_generator-info').html('<h2>Latest generated file:</h2><p><strong>File location: </strong>' + response.response.data.path + '</p><p><strong>File size: </strong>' + response.response.data.size + '</p>' +
                                '<span class="et-css-remove et-generated-remove"><span class="dashicons dashicons-trash"></span>Remove</span>').removeClass('no-file-generated');
                        }
                    },
                    error: function () {
                        alert('ajax error');
                    }
                });
            },
            generator_set_counter: function(_this) {
                var size = 0,
                    i = 0,
                    counter = $('.etheme-generator-head .counter-size'),
                    counter_val = $('.etheme-generator-head .counter-value'),
                    counter_percent_val = $('.etheme-generator-head .counter-value-percent'),
                    max_size = parseInt(counter.data('max_size')),
                    stroke_start = parseInt(counter.data('stroke-dasharray-start')),
                    stroke_end = parseInt(counter.data('stroke-dasharray-end')),
                    generator_btn = $('.etheme-generator-footer button');

                $('.etheme-css-generator .et_generator-form input:not(.has-subsection):checked').each(function (e, t) {
                    i++;
                    if ($(t).attr('data-size')) {
                        size = parseFloat(parseFloat(size) + parseFloat($(t).attr('data-size'))).toFixed(1);
                    }
                });

                if (i > 1) {
                    generator_btn.removeClass('et-button-dark-grey').addClass('et-button-green').removeAttr('disabled');
                } else {
                    generator_btn.removeClass('et-button-green').addClass('et-button-dark-grey').attr('disabled', 1);
                }

                counter_val.text('~' + size + 'Kb');

                var percent_val = size / max_size * 100;
                percent_val = '~' + percent_val.toFixed(1) + '%';

                counter_percent_val.text(percent_val);

                $(counter).css('strokeDasharray', (size / max_size * stroke_start) + 'px ' + stroke_end + 'px');

                $('.etheme-page-content').addClass('primary-counted');
            },
            generator_calc_system_files: function(_this) {
                var required_section = $('.opt-section.required'),
                    required_holder = required_section.find('.size-value'),
                    required_size = required_holder.attr('data-size'),
                    input_section = required_section.find('.input-section');

                if (_this && !_this.prop('checked')) {
                    if (_this.attr('data-required')) {
                        var required = JSON.parse(_this.attr('data-required'));
                        $.each(required, function (e, t) {

                            if (generator_required.includes(e)) {
                                generator_required.splice(e, 1);
                                required_size = parseFloat(parseFloat(required_size) - parseFloat(t)).toFixed(1);
                                required_holder.html(required_size);
                                required_holder.attr('data-size', required_size);
                                input_section.find('input').attr('data-size', required_size);
                            }
                        });
                    }
                    et_panel.generator_calc_section(_this, false);
                } else if (_this) {
                    et_panel.generator_calc_section(_this, true);
                }

                $('.etheme-css-generator .et_generator-form input:checked').each(function (e, t) {
                    if (!$('.etheme-page-content').hasClass('primary-counted')) {
                        et_panel.generator_calc_section($(t), true);
                    }
                    if ($(t).attr('data-required')) {
                        var required = JSON.parse($(t).attr('data-required'));
                        $.each(required, function (e, t) {
                            if (!generator_required.includes(e)) {
                                generator_required.push(e);
                                required_size = parseFloat(parseFloat(required_size) + parseFloat(t)).toFixed(1);
                                required_holder.html(required_size);
                                required_holder.attr('data-size', required_size);
                                required_section.find('input').attr('data-size', required_size);
                            }
                        });
                    }
                });
            },
            generator_calc_section: function(_this, action) {
                if (_this.parents('.opt-section').hasClass('required')) {
                    return;
                }

                var section = _this.closest('.opt-section'),
                    section_size = section.find('.real-size').first().attr('data-size'),
                    subsection = _this.closest('.opt-subsection.has-subsection'),
                    size = subsection.find('.real-size').attr('data-size'),
                    new_size = 0,
                    new_section_size = 0;

                if (_this.hasClass('has-subsection') && $('.etheme-page-content').hasClass('primary-counted')) {
                    if (!action) {
                        new_size = 0;
                        var c_section = section.find('.opt-subsection.has-subsection input.has-subsection').parent();

                        $.each(c_section, function () {
                            var a_section = $(this).find('.real-size');
                            a_section.html(0).attr('data-size', 0);
                        });

                        new_section_size = parseFloat(parseFloat(section_size) - parseFloat(_this.attr('data-size'))).toFixed(1);
                        _this.closest('.opt-item').find('.real-size').html(new_size).attr('data-size', new_size);

                    } else {
                        var c_section = section.find('.opt-subsection.has-subsection input.has-subsection').parent();

                        $.each(c_section, function () {
                            var a_section = $(this).find('.real-size');
                            var b_section = $(this).find('.size-value').attr('data-size');
                            a_section.html(b_section).attr('data-size', b_section);
                        });

                        new_size = _this.attr('data-size');
                        _this.closest('.opt-item').find('.real-size').html(new_size).attr('data-size', new_size);
                        new_section_size = parseFloat(parseFloat(section_size) + parseFloat(_this.attr('data-size'))).toFixed(1);
                    }
                } else {
                    if (_this.hasClass('has-subsection')) {
                        return;
                    }
                    if (!action) {
                        new_size = parseFloat(parseFloat(size) - parseFloat(_this.attr('data-size'))).toFixed(1);
                        new_section_size = parseFloat(parseFloat(section_size) - parseFloat(_this.attr('data-size'))).toFixed(1);
                    } else {
                        new_size = parseFloat(parseFloat(size) + parseFloat(_this.attr('data-size'))).toFixed(1);
                        new_section_size = parseFloat(parseFloat(section_size) + parseFloat(_this.attr('data-size'))).toFixed(1);
                    }
                }

                if (new_size < 0 || isNaN(new_size)) {
                    new_size = 0;
                }

                if (new_section_size < 0 || isNaN(new_section_size)) {
                    new_section_size = 0;
                }

                subsection.find('.real-size').html(new_size).attr('data-size', new_size);
                section.find('.real-size').first().html(new_section_size).attr('data-size', new_section_size);
            },
        };

        window.et_panel = Object.assign(window.et_panel,et_generator);

        var et_generator_actions = {
            '1': {
                selector: '.opt-section.has-subsection input.input-section.has-subsection',
                type: 'change',
                callback : et_panel.generator_section_child_change
            },
            '2': {
                selector: '.opt-subsection.has-subsection input.has-subsection',
                type: 'change',
                callback : et_panel.generator_subsection_child_change
            },
            '3': {
                selector: '.opt-item input',
                type: 'change',
                callback : et_panel.generator_parent_change
            },
            '4': {
                selector: '.et-css-remove',
                type: 'click',
                callback : et_panel.generator_remove_file
            },
            '5': {
                selector: '.etheme-css-generator .et_generator-form input',
                type: 'change',
                callback : et_panel.generator_calc
            },
            '6': {
                selector: '.etheme-css-generator .et_generator-form input',
                type: 'ready',
                callback : et_panel.generator_calc
            },
            '7': {
                selector: 'form.et_generator-form',
                type: 'submit',
                callback : et_panel.generator_generate_file
            }
        }

        $.each(et_generator_actions, function (i, t) {
            if (t.type == 'ready'){
                $(document).ready(function (e) {
                    t.callback($(this),e);
                });
            } else {
                $(document).on(t.type, t.selector, function (e){
                    t.callback($(this),e);
                });
            }
        });
    });
}(jQuery,window.et_panel);