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

# Third-party modules
from flask_restx import Namespace, Resource

# Custom modules
from .data_access_object import ObservationBlockObject
from .data_access_object import SetupObject

from util.instances import dao, tpl

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"""
        print("Show a specific OB")
        return dao.show(name)

    def put(self, name):
        """Update the OB"""
        data = api.payload
        #print(data)
        dao.update(name, data)
        return "", 204

    def post(self, name):
        """Add a template to the selected OB"""
        content = dao.content(name)
        #print(type(content))
        new_data = tpl.content(api.payload)
        # print(json.dumps(new_data, indent=4))
        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)
        dao.update(name, data)
        return "", 204

