import json
from os import path

from pycs.interfaces.LabelProvider import LabelProvider as LabelProviderInterface


class LabelProvider:
    """
    database class for label providers
    """

    def __init__(self, database, row):
        self.database = database

        self.identifier = row[0]
        self.name = row[1]
        self.description = row[2]
        self.root_folder = row[3]
        self.configuration_file = row[4]

    @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)
