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

'''Automatic REST APIs'''

# System modules
import configparser
import importlib
import sys

# Third-party modules
from flask import Blueprint
from flask_restx import Api, Namespace, Resource

# Custom modules
import devices
from utils.url_stuff import build_url

from .blocks import api as blocks_api
from .environment import api as environment_api
from .templates import api as templates_api
from .testfulvio import api as testfulvio_api

api_blueprint = Blueprint('api', __name__)

api = Api(api_blueprint,
          title='Generic APIs for observatory control',
          version='1.0',
          description=['A description']
          )

base = "api." # this module

ends = configparser.ConfigParser()
ends.read('./config/api.ini')

def dynamic_import(url):
    """Dynamically import into this module api.ini files.
    """

    parts = url.split('/') # /dome/shutter/movement
    namespace = parts[1]  #  dome
    end = '/' + '/'.join(parts[2:]) # /shutter/movement

    dev_api = Namespace(namespace) # adding namespace /dome. Endpoint will be added

    dev = getattr(devices, ends.get(url,"device"))           # devices.light instance
    cls = dev.__class__.__name__                             # string "Switch"
    mod_name = cls.lower()                                   # string "switch"
    module = importlib.import_module(base + mod_name )       # module api.switch
    module_class = getattr(module, ends.get(url,"resource")) # class api.switch.State

    # Assigning endpoint to api.ShutterMovement
    dev_api.add_resource(module_class, end , resource_class_kwargs={"dev": dev})
    api.add_namespace(dev_api) # Adding to /dome: /shutter/movement

for end in ends.sections():
    dynamic_import(end)

# Apart, what is not in the api.ini.

api.add_namespace(environment_api)

api.add_namespace(blocks_api)
api.add_namespace(templates_api)

api.add_namespace(testfulvio_api)
