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

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

from .data_access_object import ObservationBlockObject as DAO
from .data_access_object import guess


api = Namespace('block', description='An Observation block')
web = Namespace('webob', description='An Observation block')

#dao = DAO(ob_folder)
#dao.create({'task': 'Build an API'})



@api.route("/<path:obname>")
class TodoListApi(Resource):
    
    def get(self, obname):
        dao = DAO("ob/"+obname+".json")
        return dao.todos

    def put(self, obname):
        dao = DAO("ob/"+obname+".json")
        data = api.payload
        for d in data:
            for key,val in d["params"].items():
                d["params"][key] = guess(val)

        return dao.update(data), 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.route("/")
# class TodoListWeb(Resource):

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

@web.route("/<path:obname>")
class TodoWeb(Resource):

    def get(self, obname):
        dao = DAO("ob/"+obname+".json")
        data = dao.todos
        return make_response(render_template("obs.html", data=data, name=obname))


# TEST########
from flask import send_file, abort
import os

@web.route('/dir/', defaults={'req_path': ''})
@web.route('/dir/<path:req_path>')
class dir_listing(Resource):
    def get(self, req_path):
        BASE_DIR = './ob/'
        # Joining the base and the requested path
        abs_path = os.path.join(BASE_DIR, req_path)

        # Return 404 if path doesn't exist
        if not os.path.exists(abs_path):
            return abort(404)

        # Check if path is a file and serve
        if os.path.isfile(abs_path):
            return send_file(abs_path)

        # Show directory contents
        files = os.listdir(abs_path)
        return files #render_template('files.html', files=files)
