#!/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 Home(Resource):

    def get(self):
        data = {}
        return make_response(render_template("per-orso.html", data=data))


@web.route("/fits")
class Fits(Resource):
       
    def get(self):
        import io
        from astropy.io import fits                
        from flask import send_file
        with open("./data/fits/test.fits", mode='rb') as hdul:
            data = hdul.read()
            fitsdata = send_file(
                io.BytesIO(data),
                mimetype='image/fits',
                as_attachment=True,
                download_name='ciccio.fits')

        return make_response(fitsdata)


@web.route("/display")
class Display(Resource):
       
    def get(self):
        data = {}
        return make_response(render_template("display.html", data=data))
