#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import render_template, make_response
from flask_restx import Namespace, Resource, fields

class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def read(self, id):
        for todo in self.todos:
            if todo["id"] == id:
                return todo

    def create(self, data):
        todo = data
        todo["id"] = self.counter = self.counter + 1
        self.todos.append(todo)
        return todo

    def update(self, id, data):
        todo = self.read(id)
        todo.update(data)
        return todo

    def delete(self, id):
        todo = self.read(id)
        self.todos.remove(todo)


DAO = TodoDAO()
DAO.create({"task": "first"})
DAO.create({"task": "second"})


#############################################
# JSON
#############################################

a = Namespace('other', description='Other tests')

@a.route("/")
class TodoListApi(Resource):

    def get(self):
        return DAO.todos

    def post(self):
        return DAO.create(api.payload), 201

@a.route("/<int:id>")
class TodoApi(Resource):

    def get(self, id):
        return DAO.read(id)

    def delete(self, id):
        DAO.delete(id)
        return "", 204

    def put(self, id):
        return DAO.update(id, api.payload)


#############################################
# WEB
#############################################

w = Namespace('other', description='Web snippets')

@w.route("/")
class TodoListWeb(Resource):

    def get(self):
        data = DAO.todos
        return make_response(render_template("old/prova.html", data=data))

@w.route("/<int:id>")
class TodoWeb(Resource):

    def get(self,id):
        data = [DAO.read(id)]
        return make_response(render_template("old/prova.html", data=data))
