from typing import Optional
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from pymongo.database import Database


#region Funzioni generali connesse a MongoDB

# Funzione di connessione al database

def connect(user : str,password : str, database : str = "INCI") -> Database:

    uri = f"mongodb+srv://{user}:{password}@ufs13.dsmvdrx.mongodb.net/?retryWrites=true&w=majority&appName=UFS13"
    client = MongoClient(uri, server_api=ServerApi('1'))
    db = client['toxinfo']
    return db

#endregion

#region Funzioni di ricerca all'interno del mio DB

# Funzione di ricerca degli elementi estratti dal cosing
def value_search(db : Database,value:str,mode : Optional[str] = None) -> Optional[dict]:
    if mode:
        json = db.toxinfo.find_one({mode:value},{"_id":0})
        if json:
            return json
        return None
    else:
        modes = ['commonName','inciName','casNo','ecNo','chemicalName','phEurName']
        for el in modes:
            json = db.toxinfo.find_one({el:value},{"_id":0})
            if json:
                return json
        return None
            
#endregion
