import pandas as pd
import argparse

def extract_events(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()

    data_lines = lines[1:]
    label_rows = []
    event_rows = []
    cur_rows = []
    event_active = False

    for i in range(len(data_lines) - 1):
        current_row = data_lines[i].strip().split(',')
        next_row = data_lines[i + 1].strip().split(',')
        # print(current_row)
        # print(next_row)

        current_f2 = int(round(float(current_row[3])) )
        current_f1 = int(current_row[2])


        if current_f2 == 1:
            event_active = True
            cur_rows.append(current_row)

        if event_active and current_f2 == 0 and current_f1 in (512, 768):
            event_active = False
            for i in range(len(cur_rows)):
                cur_rows[i][2] = str(current_f1)
                # print(cur_rows[i])
            time1 = cur_rows[0][0]
            time2 = cur_rows[-1][0]
            status = str(current_f1)
            label_rows.append([time1, str(float(time2) - float(time1)), status])
            event_rows.extend(cur_rows)
            cur_rows = []



    return label_rows

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

event_data = extract_events(f'{dirr}/Serial-Capture-Data.data')




def convert_label(code):
    if code == '512':
        return 'right'
    elif code == '768':
        return 'left'
    else:
        return 'unknown' 

for row in event_data:
    row[2] = convert_label(row[2])
    row.append(str(1))
    row.append('')

df = pd.DataFrame(event_data, columns=['Time(Seconds)', 'Length(Seconds)', 'Label(string)', 'Confidence(double)', 'Comment(string)'])

df['Time(Seconds)'] = pd.to_numeric(df['Time(Seconds)'])
df['Length(Seconds)'] = pd.to_numeric(df['Length(Seconds)'])


df.to_csv(f'{dirr}/{dirr}.label', index=False, sep=',')


df = pd.read_csv(f'{dirr}/Serial-Capture-Data.data')
selected_columns = df[['# Time (seconds)', 'f0']]
selected_columns.to_csv(f'{dirr}/{dirr}.data', index=False, sep=',')  