#####################################################################
#                                                                   #
# /user_devices/FastComtecMCS8A/blacs_workers.py                    #
#                                                                   #
# Jan 2023, Stephan Roschinski                                      #
#                                                                   #
#                                                                   #
#####################################################################
from ctypes import * 
from . import spcm_config_start
import subprocess
import time
from . import mcs8a_structures
from blacs.tab_base_classes import Worker

class MCS8AWorker(Worker):

    def init(self):
        self.config = spcm_config_start.setup
        self.batch_file = self.config.get_config_key('Settings', 'batch_file')
        self.process = subprocess.Popen(self.batch_file) # run batch file
        # Do the rest
        self.dll_path  = self.config.get_config_key('Settings', 'dll_path')
        self.dll=WinDLL(self.dll_path) #put DLL path into the conf file
        print('init completed')
    
    def transition_to_buffered(self, device_name, h5_file, initial_values, fresh):
        self.h5file = h5_file
        return {}

    def transition_to_manual(self):

        
        print('tranistion to manual')

        return {}
    
    def program_manual(self, values):
        return {}
    
    def check_remote_values(self):
        return True

    def abort_buffered(self):
        return self.transition_to_manual()

    def abort_transition_to_buffered(self):
        return True



    #these methods need to be implemented differently 
    def get_status(self):                          
        status = ACQSTATUS()
        self.dll.GetStatusData(byref(status),0)            # Get status stored in the DLL
        return status
    
    def set_settings(self):
        conf_file = self.config.get_config_key('Settings', 'configuration_file')
        print(conf_file)
        self.dll.RunCmd(0,c_char_p(bytes('loadcnf ' + conf_file, 'utf-8')))

    def start_measurement(self):
        self.dll.RunCmd(0,c_char_p(bytes('start', 'utf-8')))
    
    def stop_measurement(self):
        self.dll.RunCmd(0,c_char_p(bytes('halt', 'utf-8')))

    def save_data(self, filename):
        data_dir = self.config.get_config_key('Settings', 'data_dir')
        self.dll.RunCmd(0,c_char_p(bytes('mpaname=' + data_dir+filename, 'utf-8')))
        self.dll.RunCmd(0,c_char_p(bytes('savempa', 'utf-8')))