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

'''REST API to edit Observation Blocks'''

# Third-party modules
from flask_restx import Namespace, Resource

# Custom modules
from utils.data_access_object import ObservationBlockObject as DAO
from utils.data_access_object import guess

dao = DAO("ob")
tpl = DAO("defaults")

api = Namespace('blocks', description='Observation blocks')

@api.route("/")
class BlockList(Resource):
    """Show and create OBs"""

    def get(self):
        """Show all observation OB files"""
        return dao.todos

    def post(self):
        """Create a new OB file based on name"""
        name = api.payload
        dao.create(name)
        return "", 204

    def delete(self):
        """Delete an OB file based on name"""
        name = api.payload
        dao.delete(name)
        return "", 204

@api.route("/<string:name>")
@api.param("name", "The uniqe name of the OB")
class Block(Resource):
    """Show a selected OB, update it, or add a new
    template in it.
    """

    def get(self, name):
        """Show a specific OB"""
        return dao.show(name)

    def put(self, name):
        """Update the OB"""
        data = api.payload
        for datum in data:
            for key, val in datum["params"].items():
                datum["params"][key] = guess(val)
        dao.update(name, data)
        return "", 204

    def post(self, name):
        """Add a template to the selected OB"""
        content = dao.content(name)
        new_data = tpl.content(api.payload)
        data = content + new_data
        dao.update(name, data)
        return "", 204

    def delete(self, name):
        """Delete a template instance in the selected OB"""
        instance = api.payload
        data = dao.content(name)
        data.pop(instance - 1) # jinjia loop starts from 1 in html
        dao.update(name, data)
        return "", 204
