import sys
import cv2
import random
import time
import pandas as pd

from pathlib import Path
HERE = Path(__file__).parent.absolute()

def main():

    input("Make sure that 'stream_eeg.py' is running. [press ENTER to continue...]")
    time.sleep(2)

    hand_to = {
        0: {
            "win": 1,
            "lose": 2,
            "draw": 0
        },
        1: {
            "win": 2,
            "lose": 0,
            "draw": 1
        },
        2: {
            "win": 0,
            "lose": 1,
            "draw": 2
        },
    }

    code2hand = {
        0: "rock",
        1: "scissors",
        2: "paper"
    }

    your_hands = [0, 1, 2] * 5
    random.shuffle(your_hands)

    labels = []

    for your_hand in your_hands:

        order = random.choice(["win", "lose", "draw"])
        my_hand = hand_to[your_hand][order]

        def show(order, my_hand):

            cv2.namedWindow("img", cv2.WINDOW_AUTOSIZE)

            img = cv2.imread( str(HERE / "src" / f"{order}.jpg") )
            cv2.imshow("img", img)
            cv2.waitKey(1)

            time.sleep(2)

            img = cv2.imread( str(HERE / "src" / f"{code2hand[my_hand]}.jpg") )
            cv2.imshow("img", img)
            cv2.waitKey(1)

            start = time.time()
            time.sleep(3)
            end = time.time()

            labels.append({"start": start, "end": end, "hand": your_hand})

        show(order, my_hand)

    cv2.destroyAllWindows()
    input("Kill 'stream_eeg.py'. [press ENTER to continue...]")

    tmp = (HERE / "data" / "raw").glob("*.csv")
    tmp = max( [int(f.stem) for f in list(tmp)] )
    eeg_data = pd.read_csv(HERE / "data" / "raw" / f"{tmp}.csv")

    if eeg_data.iloc[0].var() < eeg_data.iloc[1].var():

        adjusted_eeg_data = eeg_data.iloc[1::2]

    else:

        adjusted_eeg_data = eeg_data.iloc[0::2]

    adjusted_eeg_data.to_csv(HERE / "data" / "adjusted" / f"{tmp}.csv", index = False)

    # var_mean = eeg_data.var(axis = 1).mean()
    # adjusted_eeg_data = eeg_data.copy()
    # for index, row in eeg_data.iterrows():
    #     if row.var() < var_mean:
    #         adjusted_eeg_data = adjusted_eeg_data.drop(index = index)

    dir_to_save = HERE / "data" / "splited" / f"{tmp}"
    dir_to_save.mkdir()

    for i in range( len(labels) ):

        label = labels[i]

        target_data = adjusted_eeg_data.query(f"{label['start']} < time < {label['end']}")

        target_data.to_csv(dir_to_save / f"{i}_{label['hand']}.csv", index = False)

    print("All done!")

if __name__ == "__main__":

    main()