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

SMART_PATH = "%sSMART" % 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 = "Plot the repartition of different data on a whole genome. (This tool uses 1 input file only, the different values being stored in the tags.    See documentation to know more about it.) [Category: Visualization]"


    parser = OptionParser(description = description)
    parser.add_option("-i", "--input",dest="inputFileName",action="store",type="string",help="input file name [compulsory] [format: file in GFF3 format]")
    parser.add_option("-n", "--names",dest="names", action="store", type="string", help="name for the tags (separated by commas and no space) [compulsory] [format: string]")
    parser.add_option("-o", "--output",dest="outTarFileName",action="store",type="string", help="output file [compulsory] [format: output file tar format]")
    parser.add_option("-c", "--color",dest="colors",action="store",default=None,type="string", help="color of the lines (separated by commas and no space) [format: string]")
    parser.add_option("-f", "--format",dest="format",action="store",default="png",type="string", help="format of the output file [format: string] [default: png]")
    parser.add_option("-r", "--normalize",dest="normalize",action="store_true", default=False,help="normalize data (when panels are different) [format: bool] [default: false]")
    parser.add_option("-l", "--log",dest="log",action="store",default="",type="string", help="use log on x- or y-axis (write 'x', 'y' or 'xy') [format: string]")
    parser.add_option("-v", "--verbosity",dest="verbosity",action="store",default=1,type="int",help="trace level [format: int]")
    (options, args) = parser.parse_args()


    absPath = os.getcwd()
    print "the current path is :", absPath
    directory = "/tmp/wrappPlotRepartition"
    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/plotRepartition.py -i %s -o %s -D %s" % (SMART_PATH, options.inputFileName, outputFileName, directory)
    if options.names != None :
        cmd += " -n %s" % options.names
    else: print "You must choose tag names !"
    if options.colors != None :
        cmd += " -c %s" % options.colors
    if options.format != None:
        cmd += " -f %s" % options.format
    if options.normalize :
        cmd += " -r " 
    if options.log != "" :
        cmd += " -l %s" % options.log
    
    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)
    
