from pyOpenBCI import OpenBCICyton
import numpy as np
import time
import datetime
import sys

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

PORT = "COM4"

def main():

    SCALE_FACTOR_EEG = (4500000)/24/(2**23-1)

    board = OpenBCICyton(port = f"{PORT}", daisy = False)

    def streamer(sample):

        try:

            eeg_data = np.array(sample.channels_data) * SCALE_FACTOR_EEG
            
            with file_to_save.open(mode = "a") as f:

                f.write(f"{time.time()},{','.join([str(v) for v in eeg_data])}\n")

        except:

            board.stop_stream()
            exit()

    file_to_save = HERE / "data" / "raw" / f"{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.csv"

    with file_to_save.open(mode = "w") as f:

        f.write("time,0,1,2,3,4,5,6,7\n")

    board.start_stream(streamer)

def test():

    SCALE_FACTOR_EEG = (4500000)/24/(2**23-1)

    board = OpenBCICyton(port = f"{PORT}", daisy = False)

    def streamer(sample):

        try:

            eeg_data = np.array(sample.channels_data) * SCALE_FACTOR_EEG
            print(eeg_data)

        except:

            board.stop_stream()
            exit()

    board.start_stream(streamer)

if __name__ == "__main__":

    args = sys.argv

    if len(args) == 1:

        main()

    else:

        if args[1] == "test":

            test()
