import pickle


def obtain_drugbank_to_names(biana_cnx, drugs, output_pickle_file):
    """
    Obtains the names associated to DrugbankIDs.
    """

    cursor = biana_cnx.cursor() # Start cursor to MySQL

    query = (''' SELECT N.value 
                 FROM externalEntityDrugBankID D, externalEntityName N 
                 WHERE D.externalEntityID = N.externalEntityID AND (N.type = "unique" OR N.type = "brand") AND D.value = %s
             ''')

    drugbank_to_names = {}
    for drug in drugs:
        cursor.execute(query, (drug,))
        names = set()
        for items in cursor:
            for name in items:
                names.add(name)
        if len(names)>0:
            for name in names:
                drugbank_to_names.setdefault(drug, set())
                drugbank_to_names[drug].add(name.lower())

    cursor.close()

    print(drugbank_to_names)
    pickle.dump(drugbank_to_names, open(output_pickle_file, 'wb'))

    return drugbank_to_names