#================================================================
#================================================================
# API-CNT(WDM) for Device with sampling function
# Infinite sampling sample
# Sampling condition setting file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccnt
from ConditionUI import ConditionWindowUI


#========================================
# ConditionWindow Class
#========================================
class ConditionWindow:
    #========================================
    # Initialization function
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.CHANNEL_NUM = 4                                          # Max channel number
        self.start_trg_table = (ccnt.CNTS_START_SOFT,                 # Software Start
                                ccnt.CNTS_START_EXT_RISE,             # External Signal Rising
                                ccnt.CNTS_START_EXT_FALL,             # External Signal Falling
                                ccnt.CNTS_START_CNTMATCH_CH0_REG0,    # Count-match Ch0 Compare-register 0
                                ccnt.CNTS_START_CNTMATCH_CH1_REG0,    # Count-match Ch1 Compare-register 0
                                ccnt.CNTS_START_CNTMATCH_CH2_REG0,    # Count-match Ch2 Compare-register 0
                                ccnt.CNTS_START_CNTMATCH_CH3_REG0,    # Count-match Ch3 Compare-register 0
                                ccnt.CNTS_START_CNTMATCH_CH0_REG1,    # Count-match Ch0 Compare-register 1
                                ccnt.CNTS_START_CNTMATCH_CH1_REG1,    # Count-match Ch1 Compare-register 1
                                ccnt.CNTS_START_CNTMATCH_CH2_REG1,    # Count-match Ch2 Compare-register 1
                                ccnt.CNTS_START_CNTMATCH_CH3_REG1)    # Count-match Ch3 Compare-register 1
        self.clock_trg_table = (ccnt.CNTS_CLOCK_CLOCK,                # Internal Clock
                                ccnt.CNTS_CLOCK_EXT_TRG)              # External Clock
        self.stop_trg_table = (ccnt.CNTS_STOP_SOFT,                   # Software Stop
                               ccnt.CNTS_STOP_EXT_RISE,               # External Signal Rising
                               ccnt.CNTS_STOP_EXT_FALL,               # External Signal Falling
                               ccnt.CNTS_STOP_NUM,                    # Stop Transfer by Specified Times
                               ccnt.CNTS_STOP_CNTMATCH_CH0_REG0,      # Count-match Ch0 Compare-register 0
                               ccnt.CNTS_STOP_CNTMATCH_CH1_REG0,      # Count-match Ch1 Compare-register 0
                               ccnt.CNTS_STOP_CNTMATCH_CH2_REG0,      # Count-match Ch2 Compare-register 0
                               ccnt.CNTS_STOP_CNTMATCH_CH3_REG0,      # Count-match Ch3 Compare-register 0
                               ccnt.CNTS_STOP_CNTMATCH_CH0_REG1,      # Count-match Ch0 Compare-register 1
                               ccnt.CNTS_STOP_CNTMATCH_CH1_REG1,      # Count-match Ch1 Compare-register 1
                               ccnt.CNTS_STOP_CNTMATCH_CH2_REG1,      # Count-match Ch2 Compare-register 1
                               ccnt.CNTS_STOP_CNTMATCH_CH3_REG1)      # Count-match Ch3 Compare-register 1
        #----------------------------------------
        # Set the parent window
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = ConditionWindowUI(parent)
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_select_start_condition = self.OnSelendokComboStartTrg,
            command_select_clock_condition = self.OnSelendokComboClockTrg,
            command_select_stop_condition = self.OnSelendokComboStopTrg,
            command_condition_window_ok = self.OnOK,
            command_condition_window_cancel = self.OnClickedButtonCancel
        )
        #----------------------------------------
        # Start updating the UI
        #----------------------------------------
        self._update_ui()

    #========================================
    # UI update function
    #========================================
    def _update_ui(self):
        #----------------------------------------
        # The window screen will be set to the last selected setting
        #----------------------------------------
        self.ui.combobox_start_condition.current(self.parent.condition_window_combobox_start_condition_last_selected)
        self.ui.combobox_stop_condition.current(self.parent.condition_window_combobox_stop_condition_last_selected)
        self.ui.combobox_clock_condition.current(self.parent.condition_window_combobox_clock_condition_last_selected)
        self.ui.textbox_start_compare_value_var.set(self.parent.condition_window_textbox_start_compare_value_last_edit)
        self.ui.textbox_stop_compare_value_var.set(self.parent.condition_window_textbox_stop_compare_value_last_edit)
        self.ui.textbox_internal_clock_value_var.set(self.parent.condition_window_textbox_internal_clock_value_last_edit)
        self.ui.textbox_stop_number_value_var.set(self.parent.condition_window_textbox_stop_number_value_last_edit)
        self.ui.radiobutton_counter_start_mode.set(self.parent.condition_window_radiobutton_counter_start_mode_last_selected)
        self.ui.radiobutton_counter_stop_mode.set(self.parent.condition_window_radiobutton_counter_stop_mode_last_selected)
        self.ui.textbox_transfer_event_var.set(self.parent.condition_window_textbox_transfer_event_last_edit)
        #----------------------------------------
        # Enable or disable the control
        #----------------------------------------
        self.OnSelendokComboStartTrg()
        self.OnSelendokComboClockTrg()
        self.OnSelendokComboStopTrg()

    #========================================
    # Function name    OnSelendokComboStartTrg
    # Parameter        event    Event(Fixed to None)
    # Details          Change start condition setting
    # Return value     None
    #========================================
    def OnSelendokComboStartTrg(self, event=None):
        #----------------------------------------
        # Get start condition from the combo box
        #----------------------------------------
        selected = self.ui.combobox_start_condition.get()
        #----------------------------------------
        # Branching by start condition
        #----------------------------------------
        if selected.find("Count-match") != -1:
            self.ui.textbox_start_compare_value.config(state = 'normal')
        else:
            self.ui.textbox_start_compare_value.config(state = 'disabled')

    #========================================
    # Function name    OnSelendokComboStopTrg
    # Parameter        event    Event(Fixed to None)
    # Details          Change stop condition setting
    # Return value     None
    #========================================
    def OnSelendokComboStopTrg(self, event=None):
        #----------------------------------------
        # Get stop condition from the combo box
        #----------------------------------------
        selected = self.ui.combobox_stop_condition.get()
        #----------------------------------------
        # Branching by stop condition
        #----------------------------------------
        if selected.find("Count-match") != -1:
            self.ui.textbox_stop_compare_value.config(state = 'normal')
        else:
            self.ui.textbox_stop_compare_value.config(state = 'disabled')
        if selected == "Stop Transfer by Specified Times":
            self.ui.textbox_stop_number_value.config(state = 'normal')
        else:
            self.ui.textbox_stop_number_value.config(state = 'disabled')

    #========================================
    # Function name    OnSelendokComboClockTrg
    # Parameter        event    Event(Fixed to None)
    # Details          Change clock condition setting
    # Return value     None
    #========================================
    def OnSelendokComboClockTrg(self, event=None):
        #----------------------------------------
        # Get clock condition from the combo box
        #----------------------------------------
        selected = self.ui.combobox_clock_condition.get()
        #----------------------------------------
        # Branching by clock condition
        #----------------------------------------
        if selected == "Internal Clock":
            self.ui.textbox_internal_clock_value.config(state = 'normal')
        else:
            self.ui.textbox_internal_clock_value.config(state = 'disabled')

    #========================================
    # Function name    isnum
    # Parameter        str     String
    # Parameter        base    Base
    # Details          Function to check if a string can be converted to a number
    # Return value     True: Can be converted
    #                  False: Can not be converted
    #========================================
    @staticmethod
    def isnum(str, base):
        try:
            if 10 == base:
                int(str, 10)
            elif 16 == base:
                int(str, 16)
            else:
                float(str)
        except:
            return False
        return True

    #========================================
    # Function name    OnOK()
    # Parameter        None
    # Details          Setting completion process
    # Return value     None
    #========================================
    def OnOK(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        comp_ch_no = ctypes.c_short()                      # Channel No.
        comp_reg_no = ctypes.c_short()                     # Register No.
        start_trg = ctypes.c_short()                       # Start trigger
        clock_trg = ctypes.c_short()                       # Clock trigger
        stop_trg = ctypes.c_short()                        # Stop trigger
        start_count_mode = ctypes.c_short()                # Start mode
        stop_count_mode = ctypes.c_short()                 # Stop mode
        start_comp = ctypes.c_ulong()                      # Start comparison value
        stop_comp = ctypes.c_ulong()                       # Stop comparison value
        internal_clock = ctypes.c_ulong()                  # Internal clock
        stop_number = ctypes.c_ulong()                     # Sampling stop count

        #----------------------------------------
        # Get displayed data
        #----------------------------------------
        start_trg.value = self.start_trg_table[self.ui.combobox_start_condition.current()]
        clock_trg.value = self.clock_trg_table[self.ui.combobox_clock_condition.current()]
        stop_trg.value = self.stop_trg_table[self.ui.combobox_stop_condition.current()]
        if self.ui.radiobutton_counter_start_mode.get() == 1:
            start_count_mode.value = ccnt.CNTS_START_CNT_NOT_WITH_SAMP
        else:
            start_count_mode.value = ccnt.CNTS_START_CNT_WITH_SAMP
        if self.ui.radiobutton_counter_stop_mode.get() == 1:
            stop_count_mode.value = ccnt.CNTS_STOP_CNT_NOT_WITH_SAMP
        else:
            stop_count_mode.value = ccnt.CNTS_STOP_CNT_WITH_SAMP
        #--------------------
        # Get the start comparison value
        #--------------------
        buf = self.ui.textbox_start_compare_value_var.get()
        #--------------------
        # Check if the input value is a number
        #--------------------
        if False == self.isnum(buf, 16):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            start_comp = ctypes.c_ulong(int(buf, 16))
        #--------------------
        # Get the stop comparison value
        #--------------------
        buf = self.ui.textbox_stop_compare_value_var.get()
        #--------------------
        # Check if the input value is a number
        #--------------------
        if False == self.isnum(buf, 16):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            stop_comp = ctypes.c_ulong(int(buf, 16))
        #--------------------
        # Get the internal clock value
        #--------------------
        buf = self.ui.textbox_internal_clock_value_var.get()
        #--------------------
        # Check if the input value is a number
        #--------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            internal_clock = ctypes.c_ulong(int(buf, 10))
        #--------------------
        # Get the sampling stop count
        #--------------------
        buf = self.ui.textbox_stop_number_value_var.get()
        #--------------------
        # Check if the input value is a number
        #--------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            stop_number = ctypes.c_ulong(int(buf, 10))
        #--------------------
        # Get the sampling count for notification
        #--------------------
        buf = self.ui.textbox_transfer_event_var.get()
        #--------------------
        # Check if the input value is a number
        #--------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            self.parent.number_of_data = ctypes.c_long(int(buf, 10))
        #----------------------------------------
        # Record last settings on screen
        #----------------------------------------
        self.parent.condition_window_combobox_start_condition_last_selected = self.ui.combobox_start_condition.current()
        self.parent.condition_window_combobox_stop_condition_last_selected = self.ui.combobox_stop_condition.current()
        self.parent.condition_window_combobox_clock_condition_last_selected = self.ui.combobox_clock_condition.current()
        self.parent.condition_window_textbox_start_compare_value_last_edit = self.ui.textbox_start_compare_value_var.get()
        self.parent.condition_window_textbox_stop_compare_value_last_edit = self.ui.textbox_stop_compare_value_var.get()
        self.parent.condition_window_textbox_internal_clock_value_last_edit = self.ui.textbox_internal_clock_value_var.get()
        self.parent.condition_window_textbox_stop_number_value_last_edit = self.ui.textbox_stop_number_value_var.get()
        self.parent.condition_window_radiobutton_counter_start_mode_last_selected = self.ui.radiobutton_counter_start_mode.get()
        self.parent.condition_window_radiobutton_counter_stop_mode_last_selected = self.ui.radiobutton_counter_stop_mode.get()
        self.parent.condition_window_textbox_transfer_event_last_edit = self.ui.textbox_transfer_event_var.get()
        #----------------------------------------
        # Set sampling condition
        #----------------------------------------
        #--------------------
        # StandAlone
        #--------------------
        lret.value = ccnt.CntSetStandAlone(self.parent.id)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSetStandAlone = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        #--------------------
        # Set start condition
        #--------------------
        lret.value = ccnt.CntSetSamplingStartTrigger(self.parent.id, start_trg, start_count_mode, self.CHANNEL_NUM)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSetSamplingStartTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        if start_trg.value == ccnt.CNTS_START_CNTMATCH_CH0_REG0:
            comp_ch_no.value = 0
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH1_REG0:
            comp_ch_no.value = 1
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH2_REG0:
            comp_ch_no.value = 2
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH3_REG0:
            comp_ch_no.value = 3
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH4_REG0:
            comp_ch_no.value = 4
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH5_REG0:
            comp_ch_no.value = 5
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH6_REG0:
            comp_ch_no.value = 6
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH7_REG0:
            comp_ch_no.value = 7
            comp_reg_no.value = 0
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH0_REG1:
            comp_ch_no.value = 0
            comp_reg_no.value = 1
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH1_REG1:
            comp_ch_no.value = 1
            comp_reg_no.value = 1
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH2_REG1:
            comp_ch_no.value = 2
            comp_reg_no.value = 1
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH3_REG1:
            comp_ch_no.value = 3
            comp_reg_no.value = 1
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH4_REG1:
            comp_ch_no.value = 4
            comp_reg_no.value = 1
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH5_REG1:
            comp_ch_no.value = 5
            comp_reg_no.value = 1
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH6_REG1:
            comp_ch_no.value = 6
            comp_reg_no.value = 1
        elif start_trg.value == ccnt.CNTS_START_CNTMATCH_CH7_REG1:
            comp_ch_no.value = 7
            comp_reg_no.value = 1
        else:
            comp_ch_no.value = 0xfff
            comp_reg_no.value = 0xfff
        if comp_ch_no.value != 0xfff and comp_reg_no.value != 0xfff:
            lret.value = ccnt.CntNotifyCountUp(self.parent.id, comp_ch_no, comp_reg_no, start_comp, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntNotifyCountUp = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        #--------------------
        # Set clock condition
        #--------------------
        lret.value = ccnt.CntSetSamplingClockTrigger(self.parent.id, clock_trg)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSetSamplingClockTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        #--------------------
        # Set internal clock value
        #--------------------
        if clock_trg.value == ccnt.CNTS_CLOCK_CLOCK:
            lret.value = ccnt.CntSetSamplingInternalClock(self.parent.id, internal_clock, ccnt.CNTS_TIM_UNIT_NS)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetSamplingInternalClock = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        #--------------------
        # Set stop condition
        #--------------------
        lret.value = ccnt.CntSetSamplingStopTrigger(self.parent.id, stop_trg, stop_count_mode, self.CHANNEL_NUM)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSetSamplingStopTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        if stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH0_REG0:
            comp_ch_no.value = 0
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH1_REG0:
            comp_ch_no.value = 1
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH2_REG0:
            comp_ch_no.value = 2
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH3_REG0:
            comp_ch_no.value = 3
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH4_REG0:
            comp_ch_no.value = 4
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH5_REG0:
            comp_ch_no.value = 5
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH6_REG0:
            comp_ch_no.value = 6
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH7_REG0:
            comp_ch_no.value = 7
            comp_reg_no.value = 0
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH0_REG1:
            comp_ch_no.value = 0
            comp_reg_no.value = 1
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH1_REG1:
            comp_ch_no.value = 1
            comp_reg_no.value = 1
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH2_REG1:
            comp_ch_no.value = 2
            comp_reg_no.value = 1
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH3_REG1:
            comp_ch_no.value = 3
            comp_reg_no.value = 1
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH4_REG1:
            comp_ch_no.value = 4
            comp_reg_no.value = 1
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH5_REG1:
            comp_ch_no.value = 5
            comp_reg_no.value = 1
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH6_REG1:
            comp_ch_no.value = 6
            comp_reg_no.value = 1
        elif stop_trg.value == ccnt.CNTS_STOP_CNTMATCH_CH7_REG1:
            comp_ch_no.value = 7
            comp_reg_no.value = 1
        else:
            comp_ch_no.value = 0xfff
            comp_reg_no.value = 0xfff
        if comp_ch_no.value != 0xfff and comp_reg_no.value != 0xfff:
            lret.value = ccnt.CntNotifyCountUp(self.parent.id, comp_ch_no, comp_reg_no, stop_comp, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntNotifyCountUp = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        #--------------------
        # Set stop number
        #--------------------
        if stop_trg.value == ccnt.CNTS_STOP_NUM:
            lret.value = ccnt.CntSetSamplingStopNumber(self.parent.id, stop_number)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetSamplingStopNumber = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.condition_window.destroy()

    #========================================
    # Function name    OnClickedButtonCancel
    # Parameter        None
    # Details          Cancel button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCancel(self):
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.condition_window.destroy()