# Source code for noctua.devices

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

    '''
    Import devices using configuration files
    '''

    # System modules
    import configparser
    import importlib
    import sys
    from pathlib import Path

    # Other templates
    from ..utils.url_stuff import build_url

    this_module = sys.modules[__name__]

    nodes = configparser.ConfigParser()
    devs = configparser.ConfigParser()

    nodes.read(Path(__file__).parent.parent / 'config' / 'nodes.ini')
    devs.read(Path(__file__).parent.parent / 'config' / 'devices.ini')

    def dynamic_import(this, dev):
        """Dynamically import into this module the devices
        from the nodes.ini and devices.ini files.
        Old way:

        # from config.addresses import ASCOM_REMOTE
        # from devices import ascom
        # lamp = ascom.Switch(ASCOM_REMOTE, 2)

        """

        module = importlib.import_module(
            __package__ + "." + devs.get(dev, "module"))
        cls = getattr(module, devs.get(dev, "class"))

        node = devs.get(dev, "node")

        itn = dict(nodes.items(node))

        url = build_url(itn)

        instance_name = dev

        # Extract additional parameters based on device type

        if cls.__name__ == "Sensor":
            outlet1 = int(devs.get(dev, 'outlet1'))
            outlet2 = int(devs.get(dev, 'outlet2'))
            instance = cls(url, outlet1, outlet2)
        elif cls.__name__ == "Switch":
            outlet = int(devs.get(dev, 'outlet'))
            instance = cls(url, outlet)
        else:
            instance = cls(url)

        # Set the instance as an attribute of the current object
        setattr(this, instance_name, instance)

    for dev in devs.sections():
        print(f"importing {dev}")
        dynamic_import(this_module, dev)