from contextlib import closing
from glob import glob
from json import load
from os import path


def discover(database):
    """
    find label providers in the corresponding folder and add them to the database

    :param database:
    :return:
    """
    with closing(database.cursor()) as cursor:
        # list folders in labels/
        for folder in glob('labels/*'):
            # load distribution.json
            with open(path.join(folder, 'configuration.json'), 'r') as file:
                label = load(file)

            # extract data
            name = label['name']
            description = label['description'] if 'description' in label else None

            # save to database
            cursor.execute('''
                INSERT INTO label_providers (name, description, root_folder)
                VALUES (?, ?, ?)
                ON CONFLICT (root_folder)
                DO UPDATE SET name = ?, description = ?
            ''', (name, description, folder, name, description))
