import os,sys
sys.path.append('.')
import modules.coordsi as csi
import modules.wavacc as wav
import numpy as np
import pandas as pd
import scipy as sp
import csv

def main(input):
    if len(input) != 2:
        print('Usage: python3 ./scripts/createkpi.py <parent path of interpolation csv>')
        sys.exit(1)
    root = input[1]
    handledir = './handletrace/'
    if not os.path.exists('./fulltrace'):
        try:
            os.makedirs('./fulltrace')
        except Exception as e:
            print(e)
    listdir = os.listdir(root)
    for index in listdir:
        try:
            filepath = os.path.join(root, index)
            print(filepath)
            filename = os.path.join(index)
            original_wave=[]
            with open(filepath, 'r') as f:
                reader = csv.reader(f)
                for row in reader:
                    original_wave = row
            for x in range(0, len(original_wave)):
                original_wave[x] = float(original_wave[x])
            stroke = []
            threshold = 0.15
            s_start = 0
            s_end = 0
            for i in range(1, len(original_wave)-1):
               if original_wave[i] < -threshold and original_wave[i+1] > threshold:
                   s_start = i
               elif original_wave[i] > threshold and original_wave[i+1] < -threshold:
                   if s_start != 0:
                       s_end = i
               if s_start != 0 and s_end != 0:
                   stroke.append([s_start, s_end])
                   s_start = 0
                   s_end = 0
            df = pd.read_csv(os.path.join('./handletrace/', filename))
            df['status'] = 'idle'

            for i in stroke:
                #set df['status'] == 'in' when sroke[i][0] is same as index of df.
                df.loc[i[0]:i[0], 'status'] = 'in'
                ##set df['status'] == 'out' when sroke[i][1] is same as index of df.
                df.loc[i[1]:i[1], 'status'] = 'out'
                for frame in range(i[0]+1, i[1]):
                    df.loc[frame:frame, 'status'] = 'suction'
            df.to_csv(os.path.join('./fulltrace/', index), index=False)
        except Exception as e:
            print(e)
            continue



if __name__ == '__main__':
    try:
        main(sys.argv)
    except Exception as e:
        print(e)
        sys.exit(1)