#================================================================
#================================================================
# API-CNT(WDM) for Device with sampling function
# Counter Sample
# Notification configuration file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccnt
from NotifyUI import NotifyWindowUI


#========================================
# NotifyWindow Class
#========================================
class NotifyWindow:
    #========================================
    # Initialization function
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # Macro definition
        #----------------------------------------
        self.CHANNEL_NUM = 4    # Max channel number
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.textbox_count_reg0_value_var = [None] * self.CHANNEL_NUM  # Array for storing compare register 0 control variable
        self.textbox_count_reg0_value = [None] * self.CHANNEL_NUM      # Array for storing compare register 0 control
        self.textbox_count_reg1_value_var = [None] * self.CHANNEL_NUM  # Array for storing compare register 1 control variable
        self.textbox_count_reg1_value = [None] * self.CHANNEL_NUM      # Array for storing compare register 1 control
        #----------------------------------------
        # Set the parent window
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = NotifyWindowUI(parent)
        #----------------------------------------
        # Set the value of compare register 0 and instance array for the textbox
        #----------------------------------------
        self.textbox_count_reg0_value_var[0] = self.ui.textbox_ch0_reg0_value_var
        self.textbox_count_reg0_value[0] = self.ui.textbox_ch0_reg0_value
        self.textbox_count_reg0_value_var[1] = self.ui.textbox_ch1_reg0_value_var
        self.textbox_count_reg0_value[1] = self.ui.textbox_ch1_reg0_value
        self.textbox_count_reg0_value_var[2] = self.ui.textbox_ch2_reg0_value_var
        self.textbox_count_reg0_value[2] = self.ui.textbox_ch2_reg0_value
        self.textbox_count_reg0_value_var[3] = self.ui.textbox_ch3_reg0_value_var
        self.textbox_count_reg0_value[3] = self.ui.textbox_ch3_reg0_value
        #----------------------------------------
        # Set the value of compare register 1 and instance array for the textbox
        #----------------------------------------
        self.textbox_count_reg1_value_var[0] = self.ui.textbox_ch0_reg1_value_var
        self.textbox_count_reg1_value[0] = self.ui.textbox_ch0_reg1_value
        self.textbox_count_reg1_value_var[1] = self.ui.textbox_ch1_reg1_value_var
        self.textbox_count_reg1_value[1] = self.ui.textbox_ch1_reg1_value
        self.textbox_count_reg1_value_var[2] = self.ui.textbox_ch2_reg1_value_var
        self.textbox_count_reg1_value[2] = self.ui.textbox_ch2_reg1_value
        self.textbox_count_reg1_value_var[3] = self.ui.textbox_ch3_reg1_value_var
        self.textbox_count_reg1_value[3] = self.ui.textbox_ch3_reg1_value
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_notify_window_ok = self.OnOK,
            command_notify_window_cancel = self.OnClickedButtonCancel
        )
        #----------------------------------------
        # Start updating the UI
        #----------------------------------------
        self._update_ui()

    #========================================
    # UI update function
    #========================================
    def _update_ui(self):
        ch_no = ctypes.c_short()   # Channel No.

        #----------------------------------------
        # The window screen will be set to the last selected setting
        #----------------------------------------
        for ch_no.value in range(self.CHANNEL_NUM):
            self.textbox_count_reg0_value_var[ch_no.value].set(self.parent.notify_window_textbox_compare_reg0_last_edit[ch_no.value])
            self.textbox_count_reg1_value_var[ch_no.value].set(self.parent.notify_window_textbox_compare_reg1_last_edit[ch_no.value])
        self.ui.radiobutton_error_var.set(self.parent.notify_window_radiobutton_error_last_selected)
        self.ui.radiobutton_carry_borrow_var.set(self.parent.notify_window_radiobutton_carry_borrow_last_selected)
        #----------------------------------------
        # Disables a control for a channel that does not exist on the device.
        #----------------------------------------
        for ch_no.value in range(self.CHANNEL_NUM):
            #----------------------------------------
            # Disables the display when the number of loops exceeds the total number of channels.
            #----------------------------------------
            if ch_no.value >= self.parent.channel_num.value:
                self.textbox_count_reg0_value[ch_no.value].config(state = 'disabled')
                self.textbox_count_reg1_value[ch_no.value].config(state = 'disabled')
            #----------------------------------------
            # Enables the display when the number of loops is less than or equal to the total number of channels.
            #----------------------------------------
            else:
                self.textbox_count_reg0_value[ch_no.value].config(state = 'normal')
                self.textbox_count_reg1_value[ch_no.value].config(state = 'normal')

    #========================================
    # 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
        ch_no = ctypes.c_short()                           # Channel No.
        reg_no = ctypes.c_short()                          # Register No.
        comp_data_type1 = ctypes.c_ulong * 4               # Comparison value type 1
        comp_data_type2 = comp_data_type1 * 4              # Comparison value type 2
        comp_data = comp_data_type2()                      # Comparison value

        #----------------------------------------
        # Get setting information
        #----------------------------------------
        for ch_no.value in range(self.parent.channel_num.value):
            #--------------------
            # Get the value of REG0
            #--------------------
            buf = self.textbox_count_reg0_value_var[ch_no.value].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:
                comp_data[ch_no.value][0] = ctypes.c_ulong(int(buf))
            #--------------------
            # Get the value of REG1
            #--------------------
            buf = self.textbox_count_reg1_value_var[ch_no.value].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:
                comp_data[ch_no.value][1] = ctypes.c_ulong(int(buf))
            #----------------------------------------
            # Record last settings on screen
            #----------------------------------------
            self.parent.notify_window_textbox_compare_reg0_last_edit[ch_no.value] = self.textbox_count_reg0_value_var[ch_no.value].get()
            self.parent.notify_window_textbox_compare_reg1_last_edit[ch_no.value] = self.textbox_count_reg1_value_var[ch_no.value].get()
        #----------------------------------------
        # Record last settings on screen
        #----------------------------------------
        self.parent.notify_window_radiobutton_error_last_selected = self.ui.radiobutton_error_var.get()
        self.parent.notify_window_radiobutton_carry_borrow_last_selected = self.ui.radiobutton_carry_borrow_var.get()
        #----------------------------------------
        # Set the configuration information to the device
        #----------------------------------------
        for ch_no.value in range(0, self.parent.channel_num.value):
            for reg_no.value in range(0, 2):
                #----------------------------------------
                # Set count match notification & compare register
                #----------------------------------------
                lret.value = ccnt.CntNotifyCountUp(self.parent.id, ch_no, reg_no, comp_data[ch_no.value][reg_no.value], 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
        if self.ui.radiobutton_error_var.get() == 1:
            #----------------------------------------
            # Set counter error notification
            #----------------------------------------
            lret.value = ccnt.CntNotifyCounterError(self.parent.id, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntNotifyCounterError = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        if self.ui.radiobutton_carry_borrow_var.get() == 1:
            #----------------------------------------
            # Set carry/borrow notification
            #----------------------------------------
            lret.value = ccnt.CntNotifyCarryBorrow(self.parent.id, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntNotifyCarryBorrow = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.notify_window.destroy()

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