import pickle
import sys

from orgasm.indexer import Index

from backtranslate.fasta import fasta
import samples



def getIndex(config):
    '''
    
    @param config: a configuration object
    @return: an Indexer instance
    '''
    
    return Index(config['orgasm']['indexfilename'])

def getProbes(config):
    '''
    According to the configuration file and the --seeds option this function return the set
    of sequence probes to use
    
     
    @param config: a configuration object
    @return: a dictionary with gene name as key and the 
             nucleic or protein sequence as value
    @rtype: dict
    '''
    logger=config['orgasm']['logger']
    seeds =config['orgasm']['seeds']
    
    try:
        p = fasta(seeds)
        logger.info("Load probe sequences from file : %s" % seeds)
    except IOError:
        p = getattr(samples,seeds)
        logger.info("Load probe internal dataset : %s" % seeds)
                    
    return p

def getSeeds(index,probes,config,extension=".omx"):
    # looks if the internal blast was already run            
    output = config['orgasm']['outputfilename'] 
    logger=config['orgasm']['logger']
                   
    try:
        # yes, load the previous results
        seeds = pickle.load(open(output+extension))
        logger.info("Load matches from previous run : %d matches" % sum(len(seeds[i]) for i in seeds))
    except: 
        # no, run it and save the results
        logger.info("Running probes matching against reads...")
        seeds = index.lookForSeeds(probes,mincov=config['buildgraph']['mincov'])
        logger.info("==> %d matches" % sum(len(seeds[i]) for i in seeds))

        pickle.dump(seeds,open(output+extension,"w"))

    return seeds

#def reloadAssembling