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 getNormalDiv()
{
    var div = document.createElement("div");
    div.className = "operations";

    var btn_insert = getNewButton({
        href: "/create",
        className: "actions action-create",
        content: "Nuevo"
    });
    var btn_update = getNewButton({
        href: "/update",
        className: "actions action-update",
        content: "Editar"
    });
    var btn_delete = getNewButton({
        href: "/delete",
        className: "actions action-delete",
        content: "Eliminar"
    });
    div.appendChild(btn_insert);
    div.appendChild(btn_update);
    div.appendChild(btn_delete);
    return div;
}
function getAlternativeDiv()
{
    var div = document.createElement("div");
    div.className = "operations";

    var btn_insert = getNewButton({
        href: "/create",
        className: "actions action-create",
        content: "Nuevo"
    });
    var btn_update = getNewButton({
        href: "/update",
        className: "actions action-update",
        content: "Editar"
    });
    var btn_delete = getNewButton({
        href: "/delete",
        className: "actions action-delete",
        content: "Eliminar"
    });
    var btn_subrequirement = getNewButton({
        href: "/requirement",
        className: "actions action-requirement",
        content: "Nuevo Requerimiento"
    });
    div.appendChild(btn_subrequirement);
    div.appendChild(btn_insert);
    div.appendChild(btn_update);
    div.appendChild(btn_delete);
    return div;
}
function getRequirementsChildControl()
{
    var div = document.createElement("div");
    div.className = "operations";

    var btn_update = getNewButton({
        href: "/update",
        className: "actions action-update",
        content: "Editar"
    });
    var btn_delete = getNewButton({
        href: "/delete",
        className: "actions action-delete",
        content: "Eliminar"
    });
    div.appendChild(btn_update);
    div.appendChild(btn_delete);
    return div;
}
(function ($) {
    var serial = document.createElement('span');
    serial.className = 'jstree-nodeserial';

    var div = getNormalDiv();
    var divAlternative = getAlternativeDiv();
    var requirementChildControl = getRequirementsChildControl();

    $.jstree.plugins.nodeserial = 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);
                var divOperationAlt = divAlternative.cloneNode(true);
                var divChildRequirement = requirementChildControl.cloneNode(true);

                const parent = obj.childNodes[1].parentNode;
                tmp.textContent = parent.dataset.serial;
                switch (parent.dataset.document) {
                    case 'requirement':
                        obj.insertBefore(tmp, obj.childNodes[1]);
                        obj.insertBefore(divChildRequirement, obj.childNodes[3]);
                        break;
                    case 'subelement':
                    case 'requirement-parent':
                        obj.insertBefore(tmp, obj.childNodes[1]);
                        obj.insertBefore(divOperationAlt, obj.childNodes[3]);
                        break;
                    default:
                        obj.insertBefore(tmp, obj.childNodes[1]);
                        obj.insertBefore(divOperation, obj.childNodes[3]);
                        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: ['nodeserial', '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];
        }
        lastNodeSelected.style.display = "inline-block";

        if (el.data['jstree'] && el.data.jstree['url']) {
            window.location.href =  el.data.jstree['url'];
        }
        if (!el.data['document']) return;

        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 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);
                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>
                `;
                $('#tree-info').html(html);
            },
            complete: function () {
                dataParentTree.instance.set_icon(node, 'far fa-file text-blue');
            },
            error: function (xhr) {
                console.log('Error: '.xhr.statusText + xhr.responseText);
            }
        });
    }
    function getActionAttribute(node, attribute) {
        if (node.hasAttribute(attribute))
            return node.getAttribute(attribute);
        return '/';
    }
    $('.action-requirement').on('click', function (e) {
        try {
            window.location.href = getActionAttribute(e.target.parentNode.parentNode, 'data-routerequirement')
        } catch (error) {
            console.log(error);
        }
        e.preventDefault();
    });
    $('.action-create').on('click', function (e) {
        try {
            window.location.href = getActionAttribute(e.target.parentNode.parentNode, 'data-routecreate')
        } catch (error) {
            console.log(error);
        }
        e.preventDefault();
    });
    $('.action-update').on('click', function (e) {
        try {
            window.location.href = getActionAttribute(e.target.parentNode.parentNode, 'data-routeedit')
        } catch (error) {
            console.log(error);
        }
        e.preventDefault();
    });
    $('.action-delete').on('click', function (e) {
        $.confirm({
            title: 'Eliminar Elemento',
            content: 'Está seguro de eliminar ?',
            type: 'dark',
            typeAnimated: true,
            buttons: {
                confirm: {
                    text: "Confirmar!",
                    action: function () {
                        const node = e.target.parentNode.parentNode;
                        const document = node.dataset.document;
                        const route = getActionAttribute(node, 'data-routedelete');
                        $.ajax({
                            type: 'DELETE',
                            url: route,
                            data: {
                                "_token": $('meta[name="csrf-token"]').attr('content'),
                            },
                            beforeSend: function () {
                                $('#div_mensajes').removeClass('d-none');
                                $('#div_mensajes').addClass('text-center');
                                $('#mensajes').html('<img src="../storage/images/load.gif" width="5%" height="5%" />');
                            },
                            success: function (data) {
                                var d = JSON.parse(data);
                                if (d['status'] === 'OK') {
                                    //toastr.success('Registro eliminado');
                                    window.location.href =  window.location.href;
                                } else {
                                    toastr.error(d['message']);
                                }
                            },
                            error: function (xhr) {
                                console.log(xhr);
                                toastr.error('ERROR');
                            },
                            complete: function () {
                                $('#div_mensajes').addClass('d-none');
                            },
                        });
                    }
                },
                cancel: {
                    text: "Cancelar"
                }
            }
        });
        e.preventDefault();
    });
}
$(document).ready(index);
