let todos = [];

const todoHtmlList = 'list';
const todoInputBox = 'inputBx';

function addTodo(name, isCompleted)
{
  todos.push(
    {
      id: getNewTodoId(),
      name: name,
      isCompleted: isCompleted
    });

  renderTodos();
}

function removeTodo(todoId)
{

  console.log(`hit ${todoId}`);
  todos = todos.filter(sel => sel.id !== todoId);


  renderTodos();
}

function editTodo(todoId, name, isCompleted)
{

  renderTodos();
}

function getNewTodoId()
{
  if (todos.length === 0) {
    return 1;
  }
  let ids =  todos.map (sel => sel.id);
  ids.filter (sel => sel !== undefined);
  let sortedIds = ids.sort((a, b) => a-b);
  let lastElement = sortedIds[sortedIds.length-1];
  return lastElement + 1;
}

function renderTodos()
{
  // Izdzēst iepriekšējos TODO no HTML lapas
  // Delete previous TODO from HTML page
  let todoList = document.getElementById(todoHtmlList);
  todoList.innerHTML = "";
  // Pievienosi DOMam jaunos todo
  //Create DOM new todo

  for(let todo of todos)
  {
    let li = document.createElement("li");
    let t = document.createTextNode(todo.name);
    li.appendChild(t);
    document.getElementById("list").appendChild(li);

    // Create 'X' button
    let span = document.createElement("SPAN");
    let txt = document.createTextNode("\u00D7");
    span.className = "close";
    span.onclick = function() { 
      let div = this.parentElement;
      div.style.display = "none";
      removeTodo(todo.id); 
    };
    span.appendChild(txt);
    li.appendChild(span);
    

    // Add to list
    todoList.appendChild(li);
  }
}



// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');
  }
}, false);

// Create a new list item when clicking on the "Add" button
function newElement() {

  let inputValue = document.getElementById("inputBx").value;
  if (inputValue === '') {
    alert("You must write something!");
    return;
  }

  addTodo(inputValue, false);
  
  // Clear input box after validation
  document.getElementById(todoInputBox).value = "";
}

