import os, time, argparse
from datetime import datetime

from pm4py.objects.log.importer.csv import factory as csv_importer
from pm4py.objects.log.exporter.xes import factory as xes_exporter
from pm4py.objects.log.importer.xes import factory as xes_importer
from pm4py.objects.petri.importer import pnml as pnml_importer

from pm4py.evaluation.replay_fitness import factory as replay_factory
from pm4py.evaluation.precision import factory as precision_factory

from conf.settings import DATA_PATH

WORK_PATH = os.path.abspath(os.getcwd())

def readFile(f_name1, f_name2, unique=False):
    traces = []

    skipped = 0

    with open(f_name1) as file:
        file_contents = file.read()
        file_contents = file_contents.split("\n")
        print("Number of train traces are:", str(len(file_contents)))
        for row in file_contents:
            if unique:
                if row not in traces:
                    traces.append(row)
                else:
                    skipped += 1
            else:
                traces.append(row)

    with open(f_name2) as file:
        file_contents = file.read()
        file_contents = file_contents.split("\n")
        print("Number of generated traces are:", str(len(file_contents)))
        for row in file_contents:
            if unique:
                if row not in traces:
                    traces.append(row)
                else:
                    skipped += 1
            else:
                traces.append(row)

    f_traces = []
    for trace in traces:
        f_trace = []
        t = trace.split(" ")
        for i in t:
            if i != "" and "<" not in i:
                f_trace.append(i)
        if len(f_trace) > 0:
            f_traces.append(f_trace)

    print("Number of traces are:", str(len(f_traces)))
    print("Number of skipped traces are:", str(skipped))
    return f_traces

def writeToFile(file, lst):
    with open(file, 'w') as outfile:
        for entry in lst:
            outfile.write(str(entry) + "\n")

def convertToCsv(traces, to_path):
    lines = []

    case = 0
    timestamp = 0
    line = "concept:name,case:concept:name,time:timestamp"
    lines.append(line)
    for trace in traces:
        for event in trace:
            timestamp = timestamp + 1
            dt_object = datetime.fromtimestamp(timestamp)

            line = str(event) + "_" + "," + str(case) + "," + str(dt_object)
            lines.append(line)

        case = case + 1

    writeToFile(str(to_path), lines)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--system', help='Which system (e.g. pb_system_5_3)', required=True)
    parser.add_argument('-sfx', '--suffix', help='Suffix (chosen epoch, e.g. 1981)', required=True)
    parser.add_argument('-j', '--job', help='Job (0/1)', required=True)
    parser.add_argument('-pn', '--pn', help='Petri net file to evaluate', required=True)
    parser.add_argument('-strategy', '--strategy', help='naive/mh', required=True)
    args = parser.parse_args()

    system = args.system
    suffix = int(args.suffix)
    job = args.job
    pn = args.pn
    strategy = args.strategy

    if DATA_PATH is None:
        train_file = os.path.join(WORK_PATH, "data", "variants", system + "_train.txt")
        gen_file = os.path.join(WORK_PATH, "data", "avatar", "variants", system + "_relgan_" + str(suffix) + "_j" + str(job) + "_" + strategy + ".txt")
        csv_file = os.path.join(WORK_PATH, "data", "avatar", "variants", system + "_relgan_" + str(suffix) + "_j" + str(job) + "_" + strategy + "_generalization.csv")
        xes_file = os.path.join(WORK_PATH, "data", "avatar", "variants", system + "_relgan_" + str(suffix) + "_j" + str(job) + "_" + strategy + "_generalization.xes")
        pn_file = os.path.join(WORK_PATH, "data", "pns", system, pn)
    else:
        train_file = os.path.join(DATA_PATH, "variants", system + "_train.txt")
        gen_file = os.path.join(DATA_PATH, "avatar", "variants", system + "_relgan_" + str(suffix) + "_j" + str(job) + "_" + strategy + ".txt")
        csv_file = os.path.join(DATA_PATH, "avatar", "variants", system + "_relgan_" + str(suffix) + "_j" + str(job) + "_" + strategy + "_generalization.csv")
        xes_file = os.path.join(DATA_PATH, "avatar", "variants", system + "_relgan_" + str(suffix) + "_j" + str(job) + "_" + strategy + "_generalization.xes")
        pn_file = os.path.join(DATA_PATH, "pns", system, pn)


    """ READ FILES AND CONVERT TO XES """
    traces = readFile(train_file,gen_file, unique=True)
    convertToCsv(traces=traces, to_path=csv_file)
    time.sleep(1)

    log = csv_importer.import_event_log(csv_file)
    xes_exporter.export_log(log, xes_file)
    time.sleep(1)

    """ PERFORM MEASUREMENT ON PN AND XES"""
    log = xes_importer.import_log(xes_file)
    net, initial_marking, final_marking = pnml_importer.import_net(pn_file)

    fitness = replay_factory.apply(log, net, initial_marking, final_marking)
    print("Fitness=", fitness)

    precision = precision_factory.apply(log, net, initial_marking, final_marking)
    print("Precision=", precision)

    fitness = fitness["log_fitness"]
    generalization = 2 * ((fitness * precision) / (fitness + precision))

    if strategy == "mh":
        print("**** ", str(system), " Job ", str(job), " on PN ", str(pn_file), " using MH SAMPLING on suffix ", str(suffix)," ***")
    elif strategy == "naive":
        print("**** ", str(system), " Job ", str(job), " on PN ", str(pn_file), " using NAIVE SAMPLING on suffix ", str(suffix), " ***")
    else:
        raise ValueError("Unknown strategy.")
    print("AVATAR Generalization=", generalization)
[((14, 28, 14, 39), 'os.getcwd', 'os.getcwd', ({}, {}), '()', False, 'import os, time, argparse\n'), ((86, 13, 86, 38), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ({}, {}), '()', False, 'import os, time, argparse\n'), ((117, 4, 117, 17), 'time.sleep', 'time.sleep', ({(117, 15, 117, 16): '(1)'}, {}), '(1)', False, 'import os, time, argparse\n'), ((119, 10, 119, 49), 'pm4py.objects.log.importer.csv.factory.import_event_log', 'csv_importer.import_event_log', ({(119, 40, 119, 48): 'csv_file'}, {}), '(csv_file)', True, 'from pm4py.objects.log.importer.csv import factory as csv_importer\n'), ((120, 4, 120, 42), 'pm4py.objects.log.exporter.xes.factory.export_log', 'xes_exporter.export_log', ({(120, 28, 120, 31): 'log', (120, 33, 120, 41): 'xes_file'}, {}), '(log, xes_file)', True, 'from pm4py.objects.log.exporter.xes import factory as xes_exporter\n'), ((121, 4, 121, 17), 'time.sleep', 'time.sleep', ({(121, 15, 121, 16): '(1)'}, {}), '(1)', False, 'import os, time, argparse\n'), ((124, 10, 124, 43), 'pm4py.objects.log.importer.xes.factory.import_log', 'xes_importer.import_log', ({(124, 34, 124, 42): 'xes_file'}, {}), '(xes_file)', True, 'from pm4py.objects.log.importer.xes import factory as xes_importer\n'), ((125, 42, 125, 75), 'pm4py.objects.petri.importer.pnml.import_net', 'pnml_importer.import_net', ({(125, 67, 125, 74): 'pn_file'}, {}), '(pn_file)', True, 'from pm4py.objects.petri.importer import pnml as pnml_importer\n'), ((127, 14, 127, 76), 'pm4py.evaluation.replay_fitness.factory.apply', 'replay_factory.apply', ({(127, 35, 127, 38): 'log', (127, 40, 127, 43): 'net', (127, 45, 127, 60): 'initial_marking', (127, 62, 127, 75): 'final_marking'}, {}), '(log, net, initial_marking, final_marking)', True, 'from pm4py.evaluation.replay_fitness import factory as replay_factory\n'), ((130, 16, 130, 81), 'pm4py.evaluation.precision.factory.apply', 'precision_factory.apply', ({(130, 40, 130, 43): 'log', (130, 45, 130, 48): 'net', (130, 50, 130, 65): 'initial_marking', (130, 67, 130, 80): 'final_marking'}, {}), '(log, net, initial_marking, final_marking)', True, 'from pm4py.evaluation.precision import factory as precision_factory\n'), ((101, 21, 101, 87), 'os.path.join', 'os.path.join', ({(101, 34, 101, 43): 'WORK_PATH', (101, 45, 101, 51): '"""data"""', (101, 53, 101, 63): '"""variants"""', (101, 65, 101, 86): "system + '_train.txt'"}, {}), "(WORK_PATH, 'data', 'variants', system + '_train.txt')", False, 'import os, time, argparse\n'), ((105, 18, 105, 68), 'os.path.join', 'os.path.join', ({(105, 31, 105, 40): 'WORK_PATH', (105, 42, 105, 48): '"""data"""', (105, 50, 105, 55): '"""pns"""', (105, 57, 105, 63): 'system', (105, 65, 105, 67): 'pn'}, {}), "(WORK_PATH, 'data', 'pns', system, pn)", False, 'import os, time, argparse\n'), ((107, 21, 107, 79), 'os.path.join', 'os.path.join', ({(107, 34, 107, 43): 'DATA_PATH', (107, 45, 107, 55): '"""variants"""', (107, 57, 107, 78): "system + '_train.txt'"}, {}), "(DATA_PATH, 'variants', system + '_train.txt')", False, 'import os, time, argparse\n'), ((111, 18, 111, 60), 'os.path.join', 'os.path.join', ({(111, 31, 111, 40): 'DATA_PATH', (111, 42, 111, 47): '"""pns"""', (111, 49, 111, 55): 'system', (111, 57, 111, 59): 'pn'}, {}), "(DATA_PATH, 'pns', system, pn)", False, 'import os, time, argparse\n'), ((76, 24, 76, 57), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', ({(76, 47, 76, 56): 'timestamp'}, {}), '(timestamp)', False, 'from datetime import datetime\n')]