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/createinterpolation.py <path of handletrace dir> ')
        sys.exit(1)
    root = input[1]
    if not os.path.exists('./interpolation'):
        try:
            os.makedirs('./interpolation')
        except Exception as e:
            print(e)
    listdir = os.listdir(root)

    for index in listdir:
        try:
            df = wav.openDataframe(os.path.join(root, index))
            frame = list(df.index.values)
            acc = pd.Series.tolist(df['acceleration'])
            val = pd.Series.tolist(df['isValid'])
            vel = pd.Series.tolist(df['velocity'])
            merged = []
            for i in range(0, len(val)):
                merged.append([frame[i], val[i], acc[i]])
            for i in range(0, len(merged)):
                if merged[i][1] == 0 and merged[i][2] != 0:
                    merged[i][2] = 0
            valid_frame = []
            vaild_dot = []
            for i in range(0, len(merged)):
                if merged[i][1] == 1:
                    valid_frame.append(merged[i][0])
                    vaild_dot.append(merged[i][2])
            cubic_interpolation = sp.interpolate.interp1d(frame, acc, kind='cubic')
            cubic_interpolation = cubic_interpolation(frame)            
            with open(os.path.join('./interpolation', index), 'w') as f:
                #save cubic interpolation only
                writer = csv.writer(f)
                writer.writerow(cubic_interpolation)
        except Exception as e:
            print(e)
            continue


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