#================================================================
#================================================================
# API-CNT(WDM)
# Counter Sample
# Counter mode setting file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccnt
from ModeUI import ModeWindowUI


#========================================
# ModeWindow Class
#========================================
class ModeWindow:
    #========================================
    # Initialization function
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.z_phase_mode    = (ccnt.CNT_ZPHASE_NOT_USE,          # Not Use
                                ccnt.CNT_ZPHASE_NEXT_ONE,         # Next Time
                                ccnt.CNT_ZPHASE_EVERY_TIME,       # Every Time
                                -1)                               # End
        self.z_phase_logic   = (ccnt.CNT_ZLOGIC_POSITIVE,         # Positive Logic
                                ccnt.CNT_ZLOGIC_NEGATIVE,         # Negative Logic
                                -1)                               # End
        self.signal_source   = (ccnt.CNT_SIGTYPE_ISOLATE,         # Photo-coupler insulation
                                ccnt.CNT_SIGTYPE_TTL,             # TTL
                                ccnt.CNT_SIGTYPE_LINERECEIVER,    # Differential
                                -1)                               # End
        self.count_direction = (ccnt.CNT_DIR_DOWN,                # Down Count
                                ccnt.CNT_DIR_UP,                  # Up Count
                                -1)                               # End
        self.phase           = (ccnt.CNT_MODE_1PHASE,             # 1 Phase
                                ccnt.CNT_MODE_2PHASE,             # 2 Phase
                                ccnt.CNT_MODE_GATECONTROL,        # Gate Control
                                -1)                               # End
        self.mul             = (ccnt.CNT_MUL_X1,                  # x1
                                ccnt.CNT_MUL_X2,                  # x2
                                ccnt.CNT_MUL_X4,                  # x4
                                -1)                               # End
        self.sync_clear      = (ccnt.CNT_CLR_ASYNC,               # Asynchronous
                                ccnt.CNT_CLR_SYNC,                # Synchronous
                                -1)                               # End
        #----------------------------------------
        # Set the parent window
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = ModeWindowUI(parent)
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_mode_window_ok = self.OnOK,
            command_mode_window_cancel = self.OnClickedButtonCancel
        )
        #----------------------------------------
        # Start updating the UI
        #----------------------------------------
        self._update_ui()

    #========================================
    # Converts a setting value to an index that corresponds to the setting value array
    #========================================
    @staticmethod
    def _setting_to_index(setting_array, setting):
        i = 0

        while True:
            if setting_array[i] == -1:
                return -1
            if setting_array[i] == setting.value:
                return i
            i = i + 1

    #========================================
    # UI update function
    #========================================
    def _update_ui(self):
        ch_no = ctypes.c_short()               # Channel No.
        z_phase_mode = ctypes.c_short(0)       # Z-phase mode
        z_phase_logic = ctypes.c_short(1)      # Z-phase logic
        signal_source = ctypes.c_short(2)      # External signal source
        count_direction = ctypes.c_short(1)    # Count direction
        phase = ctypes.c_short(1)              # Number of phases
        mul = ctypes.c_short(0)                # Multiplier
        sync_clear = ctypes.c_short(0)         # Synchronous clear/Asynchronous clear
        filter = ctypes.c_short(0)             # Digital filter value

        #----------------------------------------
        # Get Mode
        #----------------------------------------
        ch_no.value = 0
        ccnt.CntGetZMode(self.parent.id, ch_no, ctypes.byref(z_phase_mode))
        ccnt.CntGetZLogic(self.parent.id, ch_no, ctypes.byref(z_phase_logic))
        ccnt.CntGetChannelSignal(self.parent.id, ch_no, ctypes.byref(signal_source))
        ccnt.CntGetCountDirection(self.parent.id, ch_no, ctypes.byref(count_direction))
        ccnt.CntGetOperationMode(self.parent.id, ch_no, ctypes.byref(phase), ctypes.byref(mul), ctypes.byref(sync_clear))
        ccnt.CntGetDigitalFilter(self.parent.id, ch_no, ctypes.byref(filter))
        #----------------------------------------
        # Update the acquired mode settings on the screen
        #----------------------------------------
        if self._setting_to_index(self.z_phase_mode, z_phase_mode) != -1:
            self.ui.combobox_z_phase_mode.current(self._setting_to_index(self.z_phase_mode, z_phase_mode))
        if self._setting_to_index(self.z_phase_logic, z_phase_logic) != -1:
            self.ui.combobox_z_logic.current(self._setting_to_index(self.z_phase_logic, z_phase_logic))
        if self._setting_to_index(self.signal_source, signal_source) != -1:
            self.ui.combobox_signal_source.current(self._setting_to_index(self.signal_source, signal_source))
        if self._setting_to_index(self.count_direction, count_direction) != -1:
            self.ui.combobox_count_direction.current(self._setting_to_index(self.count_direction, count_direction))
        if self._setting_to_index(self.phase, phase) != -1:
            self.ui.combobox_phase.current(self._setting_to_index(self.phase, phase))
        if self._setting_to_index(self.mul, mul) != -1:
            self.ui.combobox_mul.current(self._setting_to_index(self.mul, mul))
        if self._setting_to_index(self.sync_clear, sync_clear) != -1:
            self.ui.combobox_sync_clear.current(self._setting_to_index(self.sync_clear, sync_clear))
        self.ui.combobox_filter.current(filter.value)

    #========================================
    # 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.
        z_phase_mode = ctypes.c_short()                    # Z-phase mode
        z_phase_logic = ctypes.c_short()                   # Z-phase logic
        signal_source = ctypes.c_short()                   # External signal source
        count_direction = ctypes.c_short()                 # Count direction
        phase = ctypes.c_short()                           # Number of phases
        mul = ctypes.c_short()                             # Multiplier
        sync_clear = ctypes.c_short()                      # Synchronous clear/Asynchronous clear
        filter = ctypes.c_short()                          # Digital filter value

        #----------------------------------------
        # Get the configuration information
        #----------------------------------------
        z_phase_mode = ctypes.c_short(self.z_phase_mode[self.ui.combobox_z_phase_mode.current()])
        z_phase_logic = ctypes.c_short(self.z_phase_logic[self.ui.combobox_z_logic.current()])
        signal_source = ctypes.c_short(self.signal_source[self.ui.combobox_signal_source.current()])
        count_direction = ctypes.c_short(self.count_direction[self.ui.combobox_count_direction.current()])
        phase = ctypes.c_short(self.phase[self.ui.combobox_phase.current()])
        mul = ctypes.c_short(self.mul[self.ui.combobox_mul.current()])
        sync_clear = ctypes.c_short(self.sync_clear[self.ui.combobox_sync_clear.current()])
        filter = ctypes.c_short(self.ui.combobox_filter.current())
        #----------------------------------------
        # Set the configuration information to the device
        #----------------------------------------
        for ch_no.value in range(0, self.parent.channel_num.value):
            #----------------------------------------
            # Set the Z phase mode
            #----------------------------------------
            lret.value = ccnt.CntSetZMode(self.parent.id, ch_no, z_phase_mode)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetZMode = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # Set the Z phase logic
            #----------------------------------------
            lret.value = ccnt.CntSetZLogic(self.parent.id, ch_no, z_phase_logic)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetZLogic = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # Set the external signal source
            #----------------------------------------
            lret.value = ccnt.CntSelectChannelSignal(self.parent.id, ch_no, signal_source)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSelectChannelSignal = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # Set the direction of count
            #----------------------------------------
            lret.value = ccnt.CntSetCountDirection(self.parent.id, ch_no, count_direction)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetCountDirection = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # Set the operation mode
            #----------------------------------------
            lret.value = ccnt.CntSetOperationMode(self.parent.id, ch_no, phase, mul, sync_clear)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetOperationMode = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # Set the digital filter
            #----------------------------------------
            lret.value = ccnt.CntSetDigitalFilter(self.parent.id, ch_no, filter)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetDigitalFilter = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.mode_window.destroy()

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