#!/usr/bin/env python3
# -*- 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
#############################################

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

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

    def get(self):
        return DAO.todos

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

@api.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
#############################################

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

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

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

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

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

############################################

r = Namespace('rtc', description='RTC snippets')

@r.route("/")
class Test(Resource):

    def get(self):
        data = RTC.todos
        return make_response(render_template("test.html", data=data))

@r.route("/plots/")
class RtcPlotsListWeb(Resource):

    def get(self):
        data = RTC.todos
        return make_response(render_template("rtc_plots.html", data=data))

@r.route("/plots/<int:id>")
class RtcPlotsWeb(Resource):

    def get(self,id):
        data = [RTC.read(id)]
        return make_response(render_template("rtc_plots.html", data=data))
