/*
This file is part of SystemTestPortal.
Copyright (C) 2017  Institute of Software Technology, University of Stuttgart

SystemTestPortal is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SystemTestPortal is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SystemTestPortal.  If not, see <http://www.gnu.org/licenses/>.
*/

function assignPreconditionInputListener() {
    document.getElementById('preconditionInput').addEventListener('keypress', function (e) {
        var key = e.which || e.keyCode;
        if (key === 13) { // 13 is enter
          addPrecondition(e);
        }
    });

    $("#preconditionAdder").click(function (event) {
        addPrecondition(event);
    });

    $('.deletePrecondition').unbind().click(function (event) {
        deletePrecondition(event);
    });
}

function addPrecondition(event) {
    event.preventDefault();
    text = document.getElementById('preconditionInput').value.trim(); 

    if (text.length > 0) {
        var preconditions = document.getElementById('preconditionsList');
        var li = document.createElement("li");
        li.className = 'list-group-item preconditionItem';
    
        var span = document.createElement("span");
        span.appendChild(document.createTextNode(text));
        li.appendChild(span);

        var button = document.createElement("button");
        button.type = "button";
        button.className = "close ml-2 list-line-item btn-sm deletePrecondition pull-right";

        var buttonSpan = document.createElement("span");
        buttonSpan.className = "d-none d-sm-inline";
        buttonSpan.appendChild(document.createTextNode("x"));

        button.appendChild(buttonSpan);
        
        li.appendChild(button);

        preconditions.appendChild(li);
        assignPreconditionInputListener();         
    }
    document.getElementById('preconditionInput').value = "";
}

function deletePrecondition(event) {
    event.preventDefault();

    var li = event.target;
    // get to the parent li, iterate through tree if target element is nested in button
    while (li.nodeName == "SPAN" || li.nodeName == "BUTTON" || li.nodeName == "I") {
        li = li.parentNode;
    }
    
    li.remove();
}

function getPreconditions() {
    var arr = $('.preconditionItem').find('span:first').map(function(){
        return $(this).text();
    }).get();
    return arr;
}