import datetime, glob, os

import numpy as np
import nidaqmx as ni
import nidaqmx.constants as niconstants
import nidaqmx.stream_readers


class CompactDAQ_dummy():

    def __init__(self, log_folder):
        self._analog_task = None                 # nidaqmx task object
        self._analog_stream_reader = None        # stream reader function
        self._analog_array = None                # numpy array for sensor data
        
        self._encoder_task = None                # same as above
        self._encoder_stream_reader = None
        self._encoder_array= None

        self._sensor_data = None                # block of most recent sensor data
        self._log_folder = ""                   # folder where the tdms files are written
        self.setup_task(log_folder)


    def __enter__(self):
        return self


    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop_task()
        self.clear_task()
        self.remove_index_files()


    def setup_task(self, log_folder):
        sampling_rate = 1600.0                 # note: the analog card will round this up to 50,000/31
        samples_per_callback = 200             # shooting for 4 updates per second
        buffer_size = 10*samples_per_callback  # set the read buffer size 
        self._sensor_data = np.zeros((4, samples_per_callback))


    def _msg(self, msg):
        print(f'Dummy DAQ: {msg}')

        
    def start_task(self):
        self._msg('start_task')


    def stop_task(self):
        self._msg('stop_task')


    def clear_task(self):
        self._msg('clear_task')


    def start_logging(self):
        self._msg('start_logging')
        return # TODO: keep or lose the stuff below?
        time_str = datetime.datetime.now().strftime("-%Y-%m-%d-%H-%M-%S") # append timestamp to the filename
        filename = os.path.join(self._log_folder, "analog" + time_str + ".tdms")
        self._analog_task.in_stream.start_new_file(filename)
        self._analog_task.in_stream.logging_pause = False

        filename = os.path.join(self._log_folder, "encoder" + time_str + ".tdms")
        self._encoder_task.in_stream.start_new_file(filename)
        self._encoder_task.in_stream.logging_pause = False


    def stop_logging(self):
        self._msg('stop_logging')


    def get_data(self):
        return self._sensor_data


    def remove_index_files(self):   
        for f in glob.glob(self._log_folder + "*_index"):
            os.remove(f)
