import Task           from "./task.js"

class TaskController {
  constructor(main_view){
    this.tasks = []
    this.view  = main_view

    this.view.addEventListener("add_task", () => {
      this.createTask()
    })

    this.view.addEventListener("delete_task", event => {
      this.remoteTask(event.detail.task)      
    })
  }

  async createTask(){
    let new_task ={done: false, description: "New Task"}
    try {
      await this.create(new_task)
      this.addTask(new Task(new_task))
    } catch(error) {
      console.log(error)
      alert("Oh no! Couldn't create task.")
    }
  }

  addTask(task){
    this.view.addTaskView(task)
    task.addEventListener("change", () => this.update(task))
  }

  remoteTask(task){
    this.tasks.remove(task)
    this.view.removeTaskView(task)
    this.requestDelete(task)
  }

  async refresh(){
    let tasks_response = await fetch("/tasks", {method: "GET"})
    let tasks_data = await tasks_response.json()
  
    for (let task_data of tasks_data){ this.tasks.push(new Task(task_data)) }
    for (let task of this.tasks){ this.addTask(task) }
  }

  async create(task){
    let tasks_response = await fetch(`/tasks`, {
      method: "POST",
      body: JSON.stringify(task.data),
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if(!tasks_response.ok){
      throw new Error(`Got ${tasks_response.status} from server.`)
    }

    let task_data = await tasks_response.json()

    return task_data
  }

  async update(task){
    let tasks_response = await fetch(`/tasks/${task.id}`, {
      method: "PUT",
      body: JSON.stringify(task.data),
      headers: {
        'Content-Type': 'application/json'
      }
    })
  }

  async requestDelete(task){
    let tasks_response = await fetch(`/tasks/${task.id}`, {
      method: "DELETE"
    })
  }
}

export default TaskController