import os
import pandas as pd
from pathlib import Path
from matplotlib import pyplot as plt

DATA_FOLDER = 'ibero3'


def menu():
    """
    Prints a menu to process a file
    """
    print('1. See graphics    2. Cut Interval')
    print('3. Next            4. Go Back')
    print('5. Delete File     0. Pass')


def show_graphics(df: pd.DataFrame):
    # Create figure
    _, axs = plt.subplots(2, 2, figsize=(10, 12))

    print()
    print(df.index)

    # Make graphics
    df[["pinky", "ring", "middle", "thumb"]].plot(ax=axs[0, 0])

    df[["index_x", "index_y", "index_z"]].plot(ax=axs[0, 1])

    df[["hand_x", "hand_y", "hand_z"]].plot(ax=axs[1, 0])

    df[["hand_g_x", "hand_g_y", "hand_g_z"]].plot(ax=axs[1, 1])

    plt.tight_layout()

    plt.show()


def main():
    # Get absolute folder
    folder = Path('.').resolve()

    results = folder.joinpath('results', DATA_FOLDER)
    folder = folder.joinpath('data', DATA_FOLDER)

    os.makedirs(results, exist_ok=True)

    print("-"*40)
    print("YOUR CURRENT DATA FOLDER IS: " + str(folder))

    # Search for all JSON files in the folder
    files = [f for f in folder.iterdir() if f.suffix == '.json']

    i = 0

    while i < len(files):
        print("-"*40)
        print(f"FILE NAME: {files[i].stem}")
        print("-"*40)

        csv_path = results.joinpath(files[i].stem + '.csv')

        has_cut = csv_path.exists()

        op = ''

        df = pd.read_json(files[i])

        print(df.describe())

        show_graphics(df)

        while op not in ('4', '5'):
            # Print menu to process a file
            print()
            menu()

            op = input('Enter an option --> ')

            if op == '1':
                show_graphics(df)

            elif op == '2':
                # Select Interval
                min_index = input("\nEnter the min index: ")
                max_index = input("Enter the max index: ")

                # Get start time
                start_time = df["timestamp"][int(min_index)]

                # Cut dataframe
                df = df.iloc[int(min_index):int(max_index) + 1]

                # Update timestamps
                df["timestamp"] = df["timestamp"] - start_time

                print()
                print(df.head(10))

                correct = input("\nAre the timestamps correct? (y/n): ")

                if correct == 'y':
                    # Save csv and json file
                    df.to_csv(csv_path, index=False)

                    df.to_json(files[i], orient='records')

                    has_cut = True

            elif op == '3':
                if not has_cut:
                    print("Please cut an interval first")
                else:
                    i += 1
                    break

            elif op == '4':
                i -= 1

            elif op == '5':
                os.remove(files[i])

                files.pop(i)

            else:
                if not has_cut:
                    df.to_csv(csv_path, index=False)

                    df.to_json(files[i], orient='records')

                i += 1

                break

        print()


if __name__ == '__main__':
    main()