#!/usr/bin/env 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

dir_templates = ["log", "run"]
sort_order = [2, 3, 1]
files_to_copy = [["nn", "svg"], ["onp", "svg"], ["cppn", "svg"]]

def sortMatrix(dataMatrix):
    for index in sort_order:
        try:
            dataMatrix = sorted(dataMatrix, key=lambda indiv: float(indiv[index]), reverse=True)
        except: print "Column index: ", index, " not valid, trying next"
    return dataMatrix

def readLogFile(filename):
    input_file = open(filename, 'r')
    dataMatrix = []
    for line in input_file:
        line = line.strip()
        i = 0
        outputfilename = ""
        dataArray = []
        for string in line.split():
            dataArray.append(string)
            data = string.zfill(4)
            #dataArray.append(data)
            outputfilename += data[:4]
            outputfilename += "_"
            i += 1
        dataArray.append(outputfilename)
        dataMatrix.append(dataArray)
    return dataMatrix

def getTargetDir(file_to_copy, options):
    return options.output_dir + "/" + file_to_copy[0] + "_" + options.output + "_" + file_to_copy[1]

def copyFirst(source_directory, file_to_copy, dataMatrix, run, options):
    source_file = file_to_copy[0] + dataMatrix[0][0].zfill(4) + "." + file_to_copy[1]
    target_directory = getTargetDir(file_to_copy, options)
    target_file = run + "_" + dataMatrix[0][len(dataMatrix[0]) - 1] + "." + file_to_copy[1]
    try:
        shutil.copyfile(source_directory + "/" + source_file, target_directory + "/" + target_file)
    except IOError as io_exception:
        print "IO-error: skipping " + source_directory + "/" + source_file
        print io_exception

def parse_options():
    parser = OptionParser(usage="usage: %prog [options] <directory>\n", version="%prog 1.0")
    parser.set_defaults(input_dir=None)
    parser.add_option('-o', '--output', default="networks", action='store', type='string',
                      help='Sets the middle of the output directory name', dest='output')
    parser.add_option('-d', '--directory', default=".", action='store', type='string',
                      help='Sets the directory where the output direcotry will be created', dest='output_dir')
    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')
    (options, args) = parser.parse_args()

    options.input_dir = args[0]

    return options

def plot_dir(options):
    print "Plotting directory file"
    for file_to_copy in files_to_copy:
        output_dir_name = getTargetDir(file_to_copy, options)
        if not os.path.exists(output_dir_name): os.makedirs(output_dir_name)

    directories = Utils.getDirs(dir_templates, options.input_dir)
    print "directories", directories

    for directory in directories:
        matchFound = re.search(r"run_(\d*)", directory)
        print "matchFound:", matchFound
        if matchFound:
            try:
                run = matchFound.group(1)
                data_matrix = readLogFile(directory + "/" + options.input)
                data_matrix = sortMatrix(data_matrix)
                for file_to_copy in files_to_copy:
                    copyFirst(directory, file_to_copy, data_matrix, run, options)

            except Exception as inst:
                print "Some exception occured: " + str(type(inst))
		print inst
                continue
def main():
    options = parse_options()
    plot_dir(options)


if __name__ == '__main__':
    main()

