import sys, getopt, os, subprocess
import settings


formatExtensions = {
    'leda': 'gw',
    'list': 'txt'
}

def convert_file(input_file, output_file, convertFrom, convertTo):

    if convertFrom == 'leda' and convertTo == 'list':
        convertExecutable = '../leda2list'
    elif convertFrom == 'list' and convertTo == 'leda':
        convertExecutable = '../list2leda'

    runCommand = "%s %s > %s" % (
        convertExecutable,
        input_file,
        output_file
    )
    os.popen(runCommand)

def convert_directory(input_dir,output_dir, convertFrom, convertTo):
    print 'Converting all files in %s...' % input_dir
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    for root, subFolders, files in os.walk(input_dir):
        for f in files:
            if not os.path.exists(os.path.join(input_dir,f)):
                #print 'Path not exists: ' + os.path.join(input_dir,f)
                continue
            if not '.' + formatExtensions[convertFrom] in f:
                print 'Skipping %s' % f
                continue
            print 'Converting %s...' % f
            convert_file(os.path.join(input_dir, f), os.path.join(output_dir, f.replace('.'+formatExtensions[convertFrom],'.'+formatExtensions[convertTo])), convertFrom, convertTo)
        for subDir in subFolders:
            convert_directory(os.path.join(input_dir, subDir + '/'), os.path.join(output_dir, subDir), convertFrom, convertTo)


inputSubDir = ''
delimiter = ' '
directed = False

opts, args = getopt.getopt(sys.argv[1:], "s:d:th", ["subdir", "help"])
for o, a in opts:
    print o
    if o in ('-s', '--subdir'):
        inputSubDir = a  + '/'
    if o in ('-h','--help'):
        print """
Converts network format (for all aggregated and snapshot version)
(Note: currently supports list <-> leda)
Usage:
%s network_name convert_from convert_to
-s,--subdir      Input/output subdirectory
-h,--help        Print this""" % sys.argv[0]
        sys.exit(0)

networkName = args[0]
convertFrom = args[1]
convertTo = args[2]

inputDir = settings.BASE_INPUT_DIR + inputSubDir + networkName + '/'
outputDir = inputDir

if convertFrom == 'leda':
    inputDir += 'leda_format/'
if convertTo == 'leda':
    outputDir += 'leda_format/'

print 'Converting snapshots...'
convert_directory(inputDir + 'snapshots/', outputDir + 'snapshots/', convertFrom, convertTo)

print 'Converting aggregated networks...'
convert_directory(inputDir + 'aggregated/', outputDir + 'aggregated/', convertFrom, convertTo)
