let currentState = []
const localStorageManager = new LocalStorage()
localStorageManager.pull()
function LocalStorage() {
this.create = () =>{
localStorage.setItem('tasks', JSON.stringify(currentState))
}
this.pull = () =>{
const tasks = JSON.parse(localStorage.getItem('tasks'))
!!tasks &&
tasks.forEach((task)=>{
new Task(task).create()
})
}
}
function Task(task) {
this.create = () =>{
const item = document.createElement('li')
item.classList.add('item')
const qtd = document.createElement('strong')
qtd.id = task.id
qtd.innerHTML = task.amount
item.appendChild(qtd)
item.insertAdjacentText('beforeend', task.name)
item.appendChild(insertDelete(task.id))
const list = document.querySelector('.lista')
list.appendChild(item)
currentState.push(task)
console.log(`Task ${task.id} criada`)
return item
}
this.update = (index) =>{
const amount = document.getElementById(task.id)
amount.innerText = task.amount
currentState[index] = task
}
this.removeTask = (element, index) =>{
element.remove()
currentState.splice(index,1)
localStorageManager.create()
}
}
function insertDelete(id) {
const button = document.createElement('button');
button.innerText = 'X'
button.onclick = (e) =>{
const element = e.target.parentNode
const index = currentState.findIndex(item => item.id === id)
new Task().removeTask(element, index)
}
return button
}
function checkingExistence(name) {
const oldTask = {}
const item = currentState.find((task) => task.name === name)
oldTask.item = item
if(item) {
const index = currentState.findIndex(element => element.id === item.id)
oldTask.index = index
}
return oldTask
}
function handleSubmit(e) {
e.preventDefault();
const inputName = e.target.elements['name']
const inputAmount = e.target.elements['amount']
const task = {
name: inputName.value,
amount: inputAmount.value
}
const oldTask = checkingExistence(inputName.value)
if(!oldTask.item && inputName.value && inputAmount.value){
task.id = currentState[currentState.length-1] ? currentState[currentState.length-1].id + 1 : 0
new Task(task).create()
localStorageManager.create()
}
else if (!!oldTask.item && inputName.value && inputAmount.value){
task.id = oldTask.item.id
new Task(task).update(oldTask.index)
localStorageManager.create()
}
else{
console.log('Valor inválido')
}
}
const form = document.querySelector('.adicionar');
form.onsubmit = handleSubmit