'''
Parses log files gathered from tello.
"ratio" operation parses ratio files generated by the ratio experiments
"flight" extracts the XYZ coordinates from flight data
'''


import argparse
import csv
from collections import OrderedDict



def main():
    parser = argparse.ArgumentParser(description="Parser of Tello log files.")
    parser.add_argument("--op", '-p', dest="OPERATION", choices=["ratio", "flight"])
    parser.add_argument("--files", "-f", nargs="+", dest="FILESLIST")
    parser.add_argument("--output", "-o", dest="OUTPUT", default="output.txt")
    args = parser.parse_args()

    if args.OPERATION == "ratio":
        parse_ratio_test_logs(args.FILESLIST, args.OUTPUT)
    elif args.OPERATION == "flight":
        parse_flight_log(args.FILESLIST)


def parse_flight_log(fileslist):

    for file in fileslist:
        with open(file,"r") as source:
            rdr= csv.reader(source)
            with open(file + ".out","w+") as result:
                wtr= csv.writer(result)
                wtr.writerow(("X", "Y", "Z"))
                for r in rdr:
                    wtr.writerow((r[1], r[2], r[3]))


def parse_ratio_test_logs(filelist, output):
    values = {}

    with open(output, "w+") as f:
        f.write("Ratio,Distance\n")

    for file in filelist:
        with open(file, 'r') as f:
            for line in f:
                line = line.rstrip("/n")
                split = line.split(',')

                if not line.startswith('#'):

                    try:
                        key = round(float(split[0]), 3)
                        value = float(split[2])* 100
                        if key not in values:
                            values[key] = [value]
                        else:
                            values[key].append(value)
                    except Exception as err:
                        print(err)

    values = OrderedDict(sorted(values.items()))
    
    with open(output, "a+") as f:
        for k in values.keys():
            print(str(k) + ":\t" + str(len(values[k])) + " values")
            average = round(sum(values[k]) / len(values[k]), 1)
            f.write(str(k) + "," + str(average) + "\n")


if __name__ == '__main__':
    main()