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 getAdapters(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']
    adapt5 =config['orgasm']['adapt5']
    adapt3 =config['orgasm']['adapt3']
    
    try:
        p3 = fasta(adapt3).values()
        logger.info("Load 3' adapter sequences from file : %s" % adapt3)
    except IOError:
        p3 = getattr(samples,adapt3)
        logger.info("Load 3' adapter internal dataset : %s" % adapt3)
                    
    try:
        p5 = fasta(adapt5).values()
        logger.info("Load 5' adapter sequences from file : %s" % adapt5)
    except IOError:
        p5 = getattr(samples,adapt5)
        logger.info("Load 5' adapter internal dataset : %s" % adapt5)
                    
    return (p3,p5)


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