import pandas as pnd
import gempipe


from ..commons import load_minimal_media
from ..commons import adjust_biomass_equation
from ..commons import get_biomass_dict
from ..commons import apply_medium_given_column



def precursors_on_media(logger, model, universe, expcon, media, varprec, precursors):
    
    
    # if working with the universe, load the minmal media from the assets
    if expcon == None and media == None and varprec == None:  
        expcon, media = load_minimal_media()
        varprec = adjust_biomass_equation(logger, model, universe, 1.0)
    
    
    # get biomass precursors to check (all, even if not strain-specific): 
    biomass_mids = []
    for value in get_biomass_dict().values(): biomass_mids = biomass_mids + value
    
    
    # check if requested
    df_E = pnd.DataFrame()
    if not precursors:
        return df_E
    
    
    # prepare sheet for excel output
    df_E['name'] = None
    df_E['cond'] = None
    df_E['coeff'] = None
    for mid in biomass_mids:
        df_E.loc[mid, 'name'] = universe.metabolites.get_by_id(mid).name
        df_E.loc[mid, 'coeff'] = 0.01
        if mid in varprec.keys():
            df_E.loc[mid, 'cond'] = f'conditional'
            if mid not in [m.id for m in  model.reactions.Biomass.reactants]:  
                df_E.loc[mid, 'coeff'] = 'removed'
        else:
            df_E.loc[mid, 'cond'] = '/'

        
    # get involved media:
    if media == '-':
        logger.info(f"No media provided: blocked biomass precursors check will be skipped.")
        return df_E
    media = media.split(',')
    # at least 1 medium must exist:
    if any([i in expcon['media'].columns for i in media])==False:
        logger.error(f"None of the provided media IDs exist. Available media are {list(expcon['media'].columns)}.")
        return 1
            
    
    logger.info(f"Checking blocked biomass precursors on {len(media)} media...")
    for medium in media:
        if medium not in expcon['media'].columns:
            logger.info(f"Medium '{medium}' does not exists and will be ignored.")
            continue
        # create dedicated column on the excel output
        df_E[f'{medium}'] = None
        logger.debug(f"Checking blocked biomass precursors on medium '{medium}'...")
            
            
        # apply medium :
        response = apply_medium_given_column(logger, model, medium, expcon['media'][medium])
        if response == 1: return 1
    
            
        # check separately for each biomass precursor:
        for mid in biomass_mids:
            # skip conditional precursors: 
            if mid in [m.id for m in model.reactions.Biomass.reactants]:
                
            
                response, flux, status = gempipe.can_synth(model, mid=mid)
                if response == True:
                    df_E.loc[mid, f'{medium}'] = '/'
                else:
                    df_E.loc[mid, f'{medium}'] = 'blocked'
    
    
    return df_E
