const Sugar = require('sugar')

Sugar.extend()

const Koa    = require('koa')
const logger = require('koa-logger')
const Router = require('@koa/router')
const serve  = require('koa-static')
const bodyParser = require('koa-bodyparser')
const router = new Router()

let tasks = [
  {id: 1, done: true,  description: "Do Laundry" },
  {id: 2, done: false, description: "Do Homework"},
  {id: 3, done: false, description: "Do Chores"  },
]

router.get("/tasks", async (context) => {
  context.response.body = tasks
})

router.post("/tasks", async (context) => {
  let new_task = context.request.body
  new_task.id = Number.random(1, 1000000)
  tasks.push(new_task)
  context.response.status = 201
  context.response.body = new_task
})

router.put("/tasks/:id", async (context) => {
  let task_id           = Number(context.params["id"])
  let updated_task_data = context.request.body

  let task = tasks.find((task) => task.id === task_id )

  task.done = updated_task_data.done
  task.description = updated_task_data.description

  context.response.status = 204

})

router.delete("/tasks/:id", async (context) => {
  let task_id           = Number(context.params["id"])

  let task = tasks.find((task) => task.id === task_id )

  tasks.remove(task)
  context.response.status = 204
})

const app = new Koa()
app.use(serve(`${__dirname}/../web`))
app.use(logger())
app.use(bodyParser())
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)