#!/usr/local/bin/python
from numpy import *
import matplotlib.pyplot as plt
import re
import sys
import os.path
import shutil
from subprocess import call
from optparse import OptionParser
import createPlotUtils as Utils

#Defaults

def print_and_call(command):
    print command
    call(command)

def convert(inputFile, output, options):
    if inputFile[-4:] != '.svg': return
    if os.path.isfile("/Applications/Inkscape.app/Contents/Resources/bin/inkscape"):
        print_and_call(["/Applications/Inkscape.app/Contents/Resources/bin/inkscape", "--export-width=1024", "--without-gui", "--export-" + options.extention + "=" + output, inputFile])
    elif os.path.isfile("/home/jhuizing/bin/cairosvg"):
        print_and_call(["/home/jhuizing/bin/cairosvg", inputFile, "-o", output])

def convertFirst(directory, dataMatrix, run, options):
    convert(directory + "/onp" + dataMatrix[0][0].zfill(4) + ".svg",
            options.output + "_svg/" + run + "_" + dataMatrix[0][len(dataMatrix[0]) - 1])

def parse_options():
    parser = OptionParser(usage="usage: %prog [options] <directory>\n or: %prog [options] <dotfile.dot>", version="%prog 1.0")
    parser.set_defaults(layers=[8, 8, 4, 2, 1], dot_file=None, input_dir=None)
    parser.add_option('-o', '--output', default="substrate", action='store', type='string',
                      help='Sets the name of the output file or directory', dest='output')
    parser.add_option('-i', '--input', default="individuals.log", action='store', type='string',
                      help='Sets the name of the input file used to select the best network', dest='input')
    parser.add_option('-l', '--layers', default="8 8 4 2 1", action="store",
                      help='Set the layers for this network. The default is \"8 8 4 2 1\" ', dest='layers_string')
    parser.add_option('-s', '--simplify', action="store_true", default=False,
                      help='Simplify the network.', dest='simplify')
    parser.add_option('-e', '--extention', action='store', type='string', help='The output extention', dest='extention', default="pdf")
    (options, args) = parser.parse_args()

    options.layers = [int(i) for i in options.layers_string.split()]

    return options, args

def plot_dir(options, directories):
    print "Converting all files in directory"

    for directory in directories:
        output_dir = directory + "_" + options.extention
        if not os.path.exists(output_dir): os.makedirs(output_dir)
        try:
            for filename in os.listdir(directory):
                (root, _) = os.path.splitext(filename)
                convert(directory + "/" + filename, output_dir + "/" + root + "." + options.extention, options)
        except Exception as inst:
            print "Some exception occured: " + str(type(inst))
            print inst
            continue

def main():
    options, args= parse_options()
    plot_dir(options, args)

if __name__ == '__main__':
    main()

