from pycs import db
from pycs.database.base import NamedBaseModel

class LabelProvider(NamedBaseModel):
    """
    database class for label providers
    """

    description = db.Column(db.String)
    root_folder = db.Column(db.String, nullable=False, unique=True)

    # relationships to other models
    projects = db.relationship("Project", backref="label_provider", lazy=True)

    @property
    def configuration_path(self):
        return path.join(self.root_folder, self.configuration_file)

    def load(self) -> LabelProviderInterface:
        """
        load configuration.json and create an instance from the included code object

        :return: LabelProvider instance
        """
        # load configuration.json
        with open(self.configuration_path, 'r') as configuration_file:
            configuration = json.load(configuration_file)

        # load code
        code_path = path.join(self.root_folder, configuration['code']['module'])
        module_name = code_path.replace('/', '.').replace('\\', '.')
        class_name = configuration['code']['class']

        imported_module = __import__(module_name, fromlist=[class_name])
        class_attr = getattr(imported_module, class_name)

        # return instance
        return class_attr(self.root_folder, configuration)
