"use strict";

$(function() {

    new class {

        block;
        template;
        addBtn;

        constructor() {
            this.config();
            this.loadTemplates();
        }
        
        config() {

            let __class__ = this;

            this.block = $('#template-block').get(0);
            this.template = $('#detail-template').get(0);
            this.addBtn = $("#add-template").get(0);

            $(this.block).on('click', '[data-delete]', function() {

                if( __class__.countTemplates() < 2 ) {
                    return toastr.error('Cannot delete the field');
                };

                $(this).parents('[data-template]').remove();

            });

            $(this.addBtn).on('click', function() {
                __class__.addTemplate();
            });

        }

        loadTemplates() {
            let json = $("[data-gateway-detail]").text().trim();
            if( json == '' ) return this.addTemplate();
            json = JSON.parse( json );
            for( let key in json ) {
                let value = json[key];
                let title = key.replace("_", " ");
                title = title.charAt(0).toUpperCase() + title.slice(1);
                this.addTemplate( title, value );
            }
        }

        addTemplate(key = '', value = '') {
            let content = this.template.content.cloneNode(true);
            $(content).find("[data-name]").each(function() {
                this.value = (this.dataset.name == 'title') ? key : value;
            });
            this.block.appendChild(content);
        }

        countTemplates() {
            return $(this.block).find("[data-template]").length;
        }

    };

});