import os,getopt,sys
import settings
import utils,gdv_utils
import numpy as np

inputSubDir = ''
ignore_methods = []
opts, args = getopt.getopt(sys.argv[1:], "s:d:tzch", ["subdir","help","ignore-methods="])
for o, a in opts:
    if o in ('-s', '--subdir'):
        inputSubDir = a  + '/'
    elif o == '--ignore-methods':
        ignore_methods = a.split(',')
    elif o in ('-h','--help'):
        print """Usage:
%s network_name
-s,--subdir           Location of network directory within input/output directory
--ignore-methods      Methods to ignore (if method name contains any of the input substrings, ignore it)
-h,--help             Print this""" % sys.argv[0]
        sys.exit(0)

network_name_temp = args[0]

network_name_list = [network_name_temp]
if '/' in network_name_temp:
    a_dir = settings.BASE_INPUT_DIR + inputSubDir + network_name_temp
    network_name_list =  [name for name in os.listdir(a_dir) if os.path.isdir(os.path.join(a_dir, name))]
    inputSubDir += network_name_temp

method_times = {}

output_dir = settings.BASE_OUTPUT_DIR + '%s' % (inputSubDir)
for network_name in network_name_list:
    method_name_list = list(set(gdv_utils.getGdvsMethods(network_name,inputSubDir, only_with_gdvs=False)))
    for m in ignore_methods:
      for method in method_name_list[:]:
          if (m in method) and (method in method_name_list):
              method_name_list.remove(method)

    for method_name in method_name_list:
        method_dict = gdv_utils.getMethodDetailsDict(method_name)

        if (method_dict['type'] == 's' or method_dict['type'] == 'st') and method_dict['n']<5:
            continue

        time_file_dir = output_dir + network_name + '/counts/'
        if method_dict['type'] == 's':
            time_file_dir += 'static/'
        elif method_dict['type'] == 'st':
            time_file_dir += 'static-temporal/%s/' % method_dict['network_construction']

        #if method_dict['type'] =='st': #to fix issue with some static-temproal methods - snapshot construction is repeated twice
        #    time_file = time_file_dir + network_name + '_' + method_dict['network_construction'] + '_' + method_name + '_time.txt'
        #else:
        time_file = time_file_dir + network_name + '_' + method_name + '_time.txt'

        if os.path.exists(time_file):
            run_time = float(open(time_file).read())
            if not method_times.has_key(method_name):
                method_times[method_name] = []
            method_times[method_name].append(run_time)
        else:
            print 'No file %s' % time_file

for method in sorted(method_times, cmp = gdv_utils.compareMethodNames):
    print '%s - %.1f (%.3f); min: %.1f, max: %.1f' % (method,np.average(method_times[method]),np.std(method_times[method]),min(method_times[method]),max(method_times[method]))
