let Templates = {

    buildLabel(field){

        let label = $('<p class="round-card label"></p>');

        let labelName = $('<label><input name="label" placeholder="Nome do campo"></label>');

        labelName.hide();

        label.append(labelName);

        let typeField;

        if(field.tag) typeField = field.tag;

        if(field.technical_info){

            typeField = 'technical_info';

        }

        if(field.long_info){

            typeField = 'long_info';

        }

        if(field.free_prompt){

            typeField = 'free_prompt';

        }

        if(field.section){

            typeField = 'section';

        }

        if(field.fixed_text){

            typeField = 'fixed_text';

        }

        if(field.tag == 'hr'){

            typeField = 'vbreak';

        }

        if(undefined != field.name){

            labelName.find('input').val(field.name);
            labelName.show();

        }

        label.append(Templates.buildType(typeField, field));

        // Option type
        let type = $('<select name="type"></select>');

        type.append($('<option value="h2">Título (h2)</option>'));
        type.append($('<option value="h3">Sub-Título (h3)</option>'));
        type.append($('<option value="h4">Sub-Título (h4)</option>'));
        type.append($('<option value="p">Parágrafo (p)</option>'));
        type.append($('<option value="free_prompt">Prompt Livre</option>'));
        type.append($('<option value="technical_info">Ficha Técnica</option>'));
        type.append($('<option value="long_info">Ficha Longa</option>'));
        type.append($('<option value="fixed_text">Texto Fixo</option>'));
        type.append($('<option value="original_desc">Descrição original</option>'));
        type.append($('<option value="section">Seção</option>'));

        // Texto em lista
        type.append($('<option value="list">Lista</option>'));

        // Texto livre
        type.append($('<option value="libre">Texto Livre</option>'));

        // type.append($('<option value="vbreak">Separação Vertical (hr)</option>'));

        type.val(typeField);

        label.append(type);

        let deleteElm = $('<button class="delete">X</button>');

        deleteElm.on('click', function(){

            label.remove();

        });

        label.append(deleteElm);

        type.on('change', function(){

            let typeField = $(this).val();

            let defaultObj = {
                tag: typeField,
                name: '',
                description: ''
            }

            if(typeField == 'technical_info'){

                defaultObj = {
                    technical_info: true
                }

            }

            if(typeField == 'long_info'){

                defaultObj = {
                    long_info: true
                }

            }

            if(typeField == 'free_prompt'){

                defaultObj = {
                    free_prompt: true,
                    prompt: ''
                }

            }

            if(typeField == 'section'){

                defaultObj = {
                    section: '<h2>Seção:</h2>'
                }

            }

            if(typeField == 'fixed_text'){

                defaultObj = {
                    fixed_text: 'Texto fixo'
                }

            }

            if(typeField == 'vbreak'){

                defaultObj = {
                    tag: 'hr'
                }

            }

            if(typeField == 'h3' || typeField == 'h4' || typeField == 'original_desc' || typeField == 'list' || typeField == 'libre'){

                defaultObj = {
                    tag: typeField,
                    description: ''
                }

            }

            let elm = Templates.buildLabel(defaultObj);

            label.replaceWith(elm);

        });

        return label;

    },

    buildType(typeField, field){

        let elm;

        switch(typeField){

            case 'h3':
            case 'h4':
                elm = $('<textarea class="field" placeholder="Texto do título">' + field.description + '</textarea>');
            break;
            case 'h2':
            case 'p':
                elm = $('<textarea class="field" placeholder="Descreva o que o título deve conter">' + field.description + '</textarea>');
            break;
            case 'libre':
                elm = $('<textarea class="field" placeholder="Descreva como o texto deve ser escrito">' + field.description + '</textarea>');
            break;
            case 'free_prompt':
                elm = $('<textarea class="field" placeholder="Insira seu prompt">' + field.prompt + '</textarea>');
            break;
            case 'list':
                elm = $('<textarea class="field" placeholder="O que deve ser listado?">' + field.description + '</textarea>');
            break;
            case 'textarea':
                elm = $('<textarea class="field" placeholder=">' + field.description + '</textarea>');
            break;
            case 'original_desc':

                elm = $('<label><span>Regra de início</span><input class="field" name="startRule"></label><label><span>Regra de fim</span><input class="field" name="endRule"></label><br>');

                elm.find('input[name="startRule"]').val(field.startRule);
                elm.find('input[name="endRule"]').val(field.endRule);

            break;
            case 'fixed_text':
                elm = $('<textarea class="field" placeholder="Texto fixo">' + field.fixed_text + '</textarea>');
            break;
            case 'section':
                elm = $('<textarea class="field" placeholder="Título da seção">' + field.section + '</textarea>');
            break;
            case 'vbreak':
                elm = $('<hr>');
            break;
            default:
                elm = $('<' + typeField + '></' + typeField + '>');
            break;

        }

        return elm;

    },

    loadTemplate(){

        let template = $('.template-info [name="template"]').val();

        let templatePromise = Promise.resolve(false);

        if(template == 'new'){

            templatePromise = Promise.resolve({
                structure: JSON.stringify([
                    {
                        tag: 'h2',
                        name: 'Título',
                        description: ''
                    },
                    {
                        tag: 'p',
                        name: 'Parágrafo',
                        description: ''
                    }
                ])
            });

        } else if(template) templatePromise = Api.get('/v1/templates/' + template);

        return templatePromise.then((data) => {

            if(!data) return;

            let structure = JSON.parse(data.structure);

            $('.template-body').empty();
            $('.template-info .add-label').remove();

            for(let i = 0; i < structure.length; i++){

                let field = structure[i];

                if(!field.description) field.description = '';

                let label = Templates.buildLabel(field);

                $('.template-body').append(label);

            }

            $('.template-body').after($('<div class="add-label"><br><center><button class="add">+</button></center></div>'));

            let addElm = $('.template-info .add-label .add');

            addElm.off('click');
            addElm.on('click', function(){

                let label = Templates.buildLabel({
                    tag: 'p',
                    name: '',
                    description: ''
                });

                $('.template-body').append(label);

            });

        });

    },

    list(){

        return Api.get('/v1/templates');

    },

    load(){

        let templateList = $('.template-info [name="template"]');

        Templates.list().then((data) => {

            templateList.empty();

            data.forEach(function(template){

                let option = $('<option value="' + template.name + '">' + template.name + '</option>');

                templateList.append(option);

            });

            if(localStorage.getItem('template')){

                templateList.val(localStorage.getItem('template'));
    
            }
    
            templateList.append($('<option value="">Clonar atual</option>'));
            templateList.append($('<option value="new">Novo</option>'));

            templateList.trigger('change');

        });

    },

    askTitle(){

        return new Promise((resolve, reject) => {

            let modal = Alerts.empty('');

            let input = $('<label><span class="block">Nome do modelo</span><input type="text"></label>');
    
            $(modal).find('.dialog-body').append(input);
    
            let save = $('<button>Salvar</button>');
    
            save.on('click', function(){
    
                let name = input.find('input').val();
    
                if(name){
    
                    resolve(name);
    
                    modal.close();
    
                }
    
            });

            $(modal).find('.btns').append(save);
    

        });

    },

    async save(){

        let template = $('.template-info [name="template"]').val();

        if(template == 'new' || !template){

            template = await Templates.askTitle();

        }

        let structure = [];

        $('.template-body .label').each(function(){

            let label = $(this);

            let field = {};

            field.tag = label.find('[name="type"]').val();

            if(field.tag == 'technical_info'){

                field.technical_info = true;

            }

            if(field.tag == 'long_info'){

                field.long_info = true;

            }

            if(field.tag == 'free_prompt'){

                field.free_prompt = true;

                field.prompt = label.find('textarea').val();

            }

            if(field.tag == 'section'){

                field.section = label.find('textarea').val();

            }

            if(field.tag == 'fixed_text'){

                field.fixed_text = label.find('textarea').val();

            }

            if(field.tag == 'vbreak'){

                field.tag = 'hr';

            }

            if(field.tag == 'original_desc'){

                field.startRule = label.find('input[name="startRule"]').val();
                field.endRule = label.find('input[name="endRule"]').val();

            }

            field.name = label.find('[name="label"]').val();
            field.description = label.find('.field').val();

            if(!field.name) delete field.name;
            if(!field.description) delete field.description;

            structure.push(field);

        });

        let obj = {
            structure: structure
        };

        // Cria o template
        await Api.put('/v1/templates/' + template, obj).catch(e => {

            Alerts.ok('Ocorreu um erro', e.toString());

        });

        $('.template-info [name="template"]').val(template);

        localStorage.template = template;

        Templates.load();

    }

}

Nav.addTrigger('/dashboard/templates', function(){

    Templates.load();

});
