#! /usr/bin/env python
from optparse import OptionParser
import tarfile
import os
import re
import shutil
import subprocess

SMART_PATH = "%s/SMART" % os.environ["REPET_PATH"]

def toTar(tarFileName, directory):
    fileName = os.path.splitext(tarFileName)[0]
    fileNameBaseName = os.path.basename(fileName)
    tfile = tarfile.open(fileName + ".tmp.tar", "w")
    list = os.listdir(directory)
    for file in list:
        if re.search(str(fileNameBaseName), file):
            tfile.add(file)
    os.system("mv %s %s" % (fileName + ".tmp.tar", options.outTarFileName))
    tfile.close()
    

if __name__ == "__main__":
    
    magnifyingFactor = 1000
    
    # parse command line
    description = "Get Distribution v1.0.1: Get the distribution of the genomic coordinates on a genome. [Category: Visualization]"

    parser = OptionParser(description = description)
    parser.add_option("-i", "--input",       dest="inputFileName",     action="store",                     type="string", help="input file [compulsory] [format: file in transcript format given by -f]")
    parser.add_option("-f", "--format",      dest="format",            action="store",                     type="string", help="format of the input file [compulsory] [format: transcript file format]")
    parser.add_option("-o", "--output",      dest="outTarFileName",    action="store",                     type="string", help="output file [compulsory] [format: output file in GFF3 format]")
    parser.add_option("-r", "--reference",   dest="referenceFileName", action="store",      default=None,  type="string", help="file containing the genome [compulsory] [format: file in FASTA format]")
    parser.add_option("-n", "--nbBins",      dest="nbBins",            action="store",      default=1000,  type="int",    help="number of bins [default: 1000] [format: int]")
    parser.add_option("-2", "--bothStrands", dest="bothStrands",       action="store_true", default=False,                help="plot one curve per strand [format: bool] [default: false]")
    parser.add_option("-w", "--raw",         dest="raw",               action="store_true", default=False,                help="plot raw number of occurrences instead of density [format: bool] [default: false]")
    parser.add_option("-x", "--csv",         dest="csv",               action="store_true", default=False,                help="write a .csv file [format: bool]")
    parser.add_option("-c", "--chromosome",  dest="chromosome",        action="store",      default=None,  type="string", help="plot only a chromosome [format: string]")
    parser.add_option("-s", "--start",       dest="start",             action="store",      default=None,  type="int",    help="start from a given region [format: int]")
    parser.add_option("-e", "--end",         dest="end",               action="store",      default=None,  type="int",    help="end from a given region [format: int]")
    parser.add_option("-y", "--yMin",        dest="yMin",              action="store",      default=None,  type="int",    help="minimum value on the y-axis to plot [format: int]")
    parser.add_option("-Y", "--yMax",        dest="yMax",              action="store",      default=None,  type="int",    help="maximum value on the y-axis to plot [format: int]")
    parser.add_option("-g", "--gff",         dest="gff",               action="store_true", default=False,                help="also write GFF3 file [format: bool] [default: false]")
    parser.add_option("-H", "--height",      dest="height",            action="store",      default=None,  type="int",    help="height of the graphics [format: int] [default: 300]")
    parser.add_option("-W", "--width",       dest="width",             action="store",      default=None,  type="int",    help="width of the graphics [format: int] [default: 1000]")
    parser.add_option("-v", "--verbosity",   dest="verbosity",         action="store",      default=1,     type="int",    help="trace level [default: 1] [format: int]")
    parser.add_option("-l", "--log",         dest="log",               action="store_true", default=False,                help="write a log file [format: bool]")
    (options, args) = parser.parse_args()


    absPath = os.getcwd()
    print "the current path is :", absPath
    directory = "/tmp/wrappGetDistribution"
    print "the dir path is :", directory
    if not os.path.exists(directory):
        os.makedirs(directory)
    os.chdir(directory)
    if options.inputFileName != None and options.format != None and options.outTarFileName != None:
        outputFileName = os.path.splitext(os.path.basename(options.outTarFileName))[0]
        cmd = "python %s/Java/Python/getDistribution.py -i %s -f %s -o %s -D %s" % (SMART_PATH, options.inputFileName, options.format, outputFileName, directory)
    if options.referenceFileName != None :
        cmd += " -r %s" % options.referenceFileName
    if options.nbBins != None :
        cmd += " -n %s" % options.nbBins
    if options.chromosome :
        cmd += " -c %s" % options.chromosome 
    if options.start != None :
        cmd += " -s %s" % options.start
    if options.end != None :
        cmd += " -e %s" % options.end
    if options.yMin != None :
        cmd += " -y %s" % options.yMin
    if options.yMax != None :
        cmd += " -Y %s" % options.yMax
    if options.height != None :
        cmd += " -H %s" % options.height
    if options.width != None :
        cmd += " -W %s" % options.width
    if options.bothStrands :
        cmd += " -2" 
    if options.raw :
        cmd += " -w" 
    if options.csv :
        cmd += " -x" 
    if options.gff :
        cmd += " -g"
    if options.log :
        cmd += " -l" 
    print "cmd is: ", cmd    
    status = subprocess.call(cmd, shell=True)
    if status != 0:
            raise Exception("Problem with the execution of command!")
    toTar(options.outTarFileName, directory)
    shutil.rmtree(directory)
    
