var lastNodeSelected = undefined;

function getNewButton(props) {
    if (!props.content) return;

    let a = document.createElement("a");
    a.href = props.href;
    a.className = props.className;
    a.textContent = props.content;
    return a;
}
function getDiv() {
    var div = document.createElement("div");
    div.className = "operations";

    var btn_update = getNewButton({
        href: "/update",
        className: "actions action-update",
        content: "Actualizar"
    });
    div.appendChild(btn_update);
    return div;
}
(function ($) {
    var serial = document.createElement('span');
    serial.className = 'jstree-nodeserial';
    var div = getDiv();
    $.jstree.plugins.nodeupdaterequirement = function (options, parent) {
        this.teardown = function () {
            this.element.find(".jstree-nodeserial").remove();
            parent.teardown.call(this);
        };
        this.redraw_node = function (obj, deep, callback, force_draw) {
            obj = parent.redraw_node.call(this, obj, deep, callback, force_draw);
            if (obj) {
                var tmp = serial.cloneNode(true);
                var divOperation = div.cloneNode(true);

                const parent = obj.childNodes[1].parentNode;
                tmp.textContent = parent.dataset.serial;
                obj.insertBefore(tmp, obj.childNodes[1]);
                switch (parent.dataset.document) {
                    case 'requirement':
                        obj.insertBefore(divOperation, obj.childNodes[3]);
                    break;
                    default:
                    break;
                }
            }
            return obj;
        };
    };
})(window.jQuery);

function index() {
    $('#tree').jstree({
        core: {
            check_callback: true,
            dblclick_toggle: false
        },
        search: {
            case_insensitive: true,
            show_only_matches: false
        },
        plugins: ['nodeupdaterequirement','search']
    });
    $('#tree').on('search.jstree', function (nodes, str, res) {
        if (str.nodes.length === 0) {
            $('#tree').jstree(true).hide_all();
        }
    });
    $('#search-node').on("keyup", function (e) {
        $('#tree').jstree(true).show_all();
        $('#tree').jstree('search', $(this).val());
    });
    $('#tree').on("changed.jstree", function (e, data) {
        const el = data.instance.get_node(data.selected[0]);

        if (lastNodeSelected) {
            lastNodeSelected.style.display = "none";
        }
        const divOperation = document.getElementById(el.id);
        const nodes = divOperation.querySelectorAll(".operations");
        if (nodes.length > 0) {
            lastNodeSelected = nodes[0];
        }
        if (lastNodeSelected) {
            lastNodeSelected.style.display = "inline-block";
        }

        switch (el.data.document.toLowerCase()) {
            case 'requirement':
                requirement_consult(el, data);
                break;
            case 'subelement':
                break;
            case 'element':
                break;
            case 'requirement-parent':
                break;
            default:
                console.log('documento invalido');
                return;
        }
    });
    function getActionAttribute(node, attribute) {
        if (node.hasAttribute(attribute))
            return node.getAttribute(attribute);
        return '/';
    }
    $('.action-update').on('click', function (e) {
        try {
            window.location.href = getActionAttribute(e.target.parentNode.parentNode, 'data-routeedit')
        } catch (error) {
            console.log(error);
        }
        e.preventDefault();
    });
    function requirement_consult(node, dataParentTree) {
        $.ajax({
            url: '/requirements/consult',
            data: {
                id: node.data.id
            },
            beforeSend: function () {
                dataParentTree.instance.set_icon(node, "fas fa-spinner fa-spin");
            },
            success: function (data) {
                const requirement = JSON.parse(data);
                const links = GetLinkDocuments();
                let html = `
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-little">Requerimiento ${requirement.sections[0].sequential.value}</h3>
                    </div>
                    <div class="card-body">
                        <strong>
                            <i class="fas fa-book mr-1"></i>Descripción
                        </strong>
                        <p class="text-muted">${requirement.description}</p>
                        <hr>
                        <strong>
                            <i class="fas fa-pencil-ruler mr-1"></i>Meta
                        </strong>
                        <p class="text-muted">${requirement.goals}</p>
                        <hr>
                        <strong>
                            <i class="fas fa-file-alt mr-1"></i>Desviación
                        </strong>
                        <p class="text-muted">${requirement.deviations}</p>
                        <hr>
                        <strong>
                            <i class="fas fa-clipboard-list mr-1"></i>Materiales
                        </strong>
                        <p class="text-muted">${requirement.materials}</p>
                        <hr>
                        <strong>
                            <i class="fas fa-eye mr-1"></i>Observaciones
                        </strong>
                        <p class="text-muted">${requirement.observations}</p>
                        <hr>
                        <strong>
                            <i class="fas fa-exclamation-triangle mr-1"></i>Prioridad
                        </strong>
                        <p class="text-muted">${requirement.priorities}</p>
                    </div>
                </div>
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-little">Documentos Ejemplares</h3>
                    </div>
                    <div class="card-body">
                        <strong>
                            <i class="fas fa-book mr-1"></i>Documento
                        </strong>
                        <a id="document-sample" href="${node.data.sampledocument}" class="btn btn-info">Descargar</a>
                        <hr>
                        <strong>
                            <i class="fas fa-pencil-ruler mr-1"></i>Norma
                        </strong>
                        <a id="norm-sample" href="${node.data.samplenorm}" class="btn btn-info">Descargar</a>
                        <hr>
                    </div>
                </div>
                ${links}
                `;
                $('#tree-info').html(html);
            },
            complete: function () {
                dataParentTree.instance.set_icon(node, 'fas fa-folder-open text-blue');
            },
            error: function (xhr) {
                console.log('Error: '.xhr.statusText + xhr.responseText);
            }
        });
    }
    function GetLinkDocuments() {
        let str = '';
        console.log(docRequirement);
        if (Object.keys(docRequirement).length === 0) return '';

        str += `
            <strong>
                <i class="fas fa-book mr-1"></i>Documento
            </strong>
            <a id="document-sample" href="${docRequirement['route-document']}" class="btn btn-info">Descargar</a>
            <hr>
            `;
        str += `
            <strong>
                <i class="fas fa-book mr-1"></i>Norma
            </strong>
            <a id="document-sample" href="${docNorm['route-norm']}" class="btn btn-info">Descargar</a>
            <hr>
            `;
        let html = `
        <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-little">Mis Documentos</h3>
                    </div>
                    <div class="card-body">
                        ${str}
                    </div>
                </div>
        `;
        return html;
    }
}
$(document).ready(index);
