import csv
import argparse



parser = argparse.ArgumentParser(description='Process some directory.')
parser.add_argument('dirr', type=str, help='The directory to read from')

args = parser.parse_args()

dirr = args.dirr

input_file = f'{dirr}/Serial-Capture-Data.data'
output_file = f'{dirr}/{dirr}.label'
output_reduced_file = f'{dirr}/{dirr}.data'

def read_input_file(input_file):
    data = []
    with open(input_file, 'r') as file:
        reader = csv.reader(file)
        header = next(reader)
        for row in reader:
            time, f0, f1 = map(float, row)
            data.append({"time": time, "f0": f0, "f1": f1})
    return data

def write_reformatted_data(output_file, touches):
    with open(output_file, 'w', newline='') as csvfile:
        fieldnames = ['Time(Seconds)', 'Length(Seconds)', 'Label(string)', 'Confidence(double)', 'Comment(string)']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        
        writer.writeheader()
        for touch in touches:
            writer.writerow({
                'Time(Seconds)': touch['time'],
                'Length(Seconds)': touch['length'],
                'Label(string)': touch['label'],
                'Confidence(double)': touch['confidence'],
                'Comment(string)': touch['comment']
            })
    print(f"Label  has been saved to {output_file}")

def write_reduced_data(input_file, output_reduced_file):
    with open(input_file, 'r') as infile, open(output_reduced_file, 'w', newline='') as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)
        header = next(reader)
        writer.writerow([header[0], header[1]])
        for row in reader:
            writer.writerow([row[0], row[1]])
    print(f"Data has been saved to {output_reduced_file}")

data = read_input_file(input_file)

touches = []
start_time = None

for i in range(1, len(data)):
    if data[i]['f1'] == 1 and data[i-1]['f1'] == 0:
        start_time = data[i]['time']
    elif data[i]['f1'] == 0 and data[i-1]['f1'] == 1 and start_time is not None:
        end_time = data[i]['time']
        duration = end_time - start_time
        touches.append({"time": start_time, "length": duration, "label": "touch", "confidence": 1.0, "comment": ""})
        start_time = None

if start_time is not None:
    end_time = data[-1]['time']
    duration = end_time - start_time
    touches.append({"time": start_time, "length": duration, "label": "touch", "confidence": 1.0, "comment": ""})

write_reformatted_data(output_file, touches)

write_reduced_data(input_file, output_reduced_file)
