import requests
import json


def get_library_name(database='Human'):
    """return enrichr active enrichr library name. 
    see also: https://maayanlab.cloud/modEnrichr/

    :param str database: Select one from { 'Human', 'Mouse', 'Yeast', 'Fly', 'Fish', 'Worm' } 
    :return: a list of enrichr libraries from selected database
    
    """
    default = [ 'human','mouse','hs', 'mm',
                'homo sapiens', 'mus musculus',
                'h. sapiens', 'm. musculus']
    organism = {
                'Fly': ['fly', 'd. melanogaster', 'drosophila melanogaster'],
                'Yeast': ['yeast', 's. cerevisiae', 'saccharomyces cerevisiae'],
                'Worm': ['worm', 'c. elegans', 'caenorhabditis elegans', 'nematode'],
                'Fish': ['fish', 'd. rerio', 'danio rerio', 'zebrafish']
                }
    
    if database.lower() in default:
        database = 'Enrichr'
    else:
        for k, v in organism.items():
            if database.lower() in v :
                database = k+'Enrichr'
                break

    if not database.endswith('Enrichr'):
        raise LookupError("""No supported database. Please input one of these:
                            ('Human', 'Mouse', 'Yeast', 'Fly', 'Fish', 'Worm') """)
        return 
    # make a get request to get the gmt names and meta data from Enrichr
    # old code
    # response = requests.get('http://amp.pharm.mssm.edu/Enrichr/geneSetLibrary?mode=meta')
    # gmt_data = response.json()
    # # generate list of lib names
    # libs = []
    # # get library names
    # for inst_gmt in gmt_data['libraries']:
    #     # only include active gmts
    #     if inst_gmt['isActive'] == True:
    #         libs.append(inst_gmt['libraryName'])
    lib_url='http://amp.pharm.mssm.edu/%s/datasetStatistics'%database
    response = requests.get(lib_url)
    if not response.ok:
        raise Exception("Error getting the Enrichr libraries")
    libs_json = json.loads(response.text)
    libs = [lib['libraryName'] for lib in libs_json['statistics']]

    return sorted(libs)