#================================================================
#================================================================
# API-CNT(WDM)
# カウンタサンプル
# 比較設定ファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ccnt
from CompareUI import CompareWindowUI


#========================================
# CompareWindow クラス
#========================================
class CompareWindow:
    #========================================
    # 初期化関数
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # 変数
        #----------------------------------------
        self.compare_value = (ctypes.c_ulong * 8)()    # 比較値
        self.textbox_counter_value_var = [None] * 8    # カウンター値コントロール変数格納用の配列
        self.textbox_counter_value = [None] * 8        # カウンター値コントロール格納用の配列
        #----------------------------------------
        # 親ウィンドウの設定
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # UIの作成を開始
        #----------------------------------------
        self.ui = CompareWindowUI(parent)
        #----------------------------------------
        # テキストボックスのカウンター値とインスタンス配列を設定する
        #----------------------------------------
        self.textbox_counter_value_var[0] = self.ui.textbox_ch0_value_var
        self.textbox_counter_value[0] = self.ui.textbox_ch0_value
        self.textbox_counter_value_var[1] = self.ui.textbox_ch1_value_var
        self.textbox_counter_value[1] = self.ui.textbox_ch1_value
        self.textbox_counter_value_var[2] = self.ui.textbox_ch2_value_var
        self.textbox_counter_value[2] = self.ui.textbox_ch2_value
        self.textbox_counter_value_var[3] = self.ui.textbox_ch3_value_var
        self.textbox_counter_value[3] = self.ui.textbox_ch3_value
        self.textbox_counter_value_var[4] = self.ui.textbox_ch4_value_var
        self.textbox_counter_value[4] = self.ui.textbox_ch4_value
        self.textbox_counter_value_var[5] = self.ui.textbox_ch5_value_var
        self.textbox_counter_value[5] = self.ui.textbox_ch5_value
        self.textbox_counter_value_var[6] = self.ui.textbox_ch6_value_var
        self.textbox_counter_value[6] = self.ui.textbox_ch6_value
        self.textbox_counter_value_var[7] = self.ui.textbox_ch7_value_var
        self.textbox_counter_value[7] = self.ui.textbox_ch7_value
        #----------------------------------------
        # UIコントロールのコールバック関数を設定
        #----------------------------------------
        self.ui.setup_commands(
            command_count_value_dec = self.OnClickedRadioDec,
            command_count_value_hex = self.OnClickedRadioHex,
            command_compare_window_ok = self.OnOK,
            command_compare_window_cancel = self.OnClickedButtonCancel
        )
        #----------------------------------------
        # UIの更新を開始
        #----------------------------------------
        self._update_ui()

    #========================================
    # UIの更新関数
    #========================================
    def _update_ui(self):
        ch_no = ctypes.c_short()          # チャネルナンバー
        pulse_width = ctypes.c_short()    # パルス幅
        
        #----------------------------------------
        # ウィンドウ画面は最後に選択した設定に設定されます
        #----------------------------------------
        self.ui.radiobutton_counter_value_base_var.set(self.parent.compare_window_radiobutton_counter_value_base_var)
        self.ui.textbox_ch0_value_var.set(self.parent.compare_window_textbox_ch0_last_edit)
        self.ui.textbox_ch1_value_var.set(self.parent.compare_window_textbox_ch1_last_edit)
        self.ui.textbox_ch2_value_var.set(self.parent.compare_window_textbox_ch2_last_edit)
        self.ui.textbox_ch3_value_var.set(self.parent.compare_window_textbox_ch3_last_edit)
        self.ui.textbox_ch4_value_var.set(self.parent.compare_window_textbox_ch4_last_edit)
        self.ui.textbox_ch5_value_var.set(self.parent.compare_window_textbox_ch5_last_edit)
        self.ui.textbox_ch6_value_var.set(self.parent.compare_window_textbox_ch6_last_edit)
        self.ui.textbox_ch7_value_var.set(self.parent.compare_window_textbox_ch7_last_edit)
        for i in range(0, 8):
            if i >= self.parent.channel_num.value:
                self.textbox_counter_value[i].config(state = 'disabled')
        #----------------------------------------
        # パルス長を取得
        #----------------------------------------
        ch_no.value = 0
        ccnt.CntGetPulseWidth(self.parent.id, ch_no, ctypes.byref(pulse_width))
        self.ui.combobox_count_match_pulse.current(pulse_width.value)

    #========================================
    # 関数名    isnum
    # 引数      str     文字列
    # 引数      base    ベース
    # 詳細      文字列を数値に変換できるかどうか確認する関数
    # 戻り値    True : 変換できる
    #           False : 変換できない
    #========================================
    @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

    #========================================
    # 関数名    OnClickedRadioDec()
    # 引数      なし
    # 詳細      比較値の表示変更(10進数)
    # 戻り値    なし
    #========================================
    def OnClickedRadioDec(self):
        #----------------------------------------
        # 画面情報を更新
        #----------------------------------------
        for i in range(0, 8):
            buf = self.textbox_counter_value_var[i].get()
            #----------------------------------------
            # 入力値が数値かどうかをチェック
            #----------------------------------------
            if False == self.isnum(buf, 16):
                self.ui.show_error("Error", "入力値が無効です。")
                return
            else:
                self.textbox_counter_value_var[i].set(f"{int(buf, 16):d}")

    #========================================
    # 関数名    OnClickedRadioHex()
    # 引数      なし
    # 詳細      比較値の表示変更(16進数)
    # 戻り値    なし
    #========================================
    def OnClickedRadioHex(self):
        #----------------------------------------
        # 画面情報を更新
        #----------------------------------------
        for i in range(0, 8):
            buf = self.textbox_counter_value_var[i].get()
            #----------------------------------------
            # 入力値が数値かどうかをチェック
            #----------------------------------------
            if False == self.isnum(buf, 10):
                self.ui.show_error("Error", "入力値が無効です。")
                return
            else:
                self.textbox_counter_value_var[i].set(f"{int(buf):08X}")

    #========================================
    # 関数名    OnOK()
    # 引数      なし
    # 詳細      設定完了処理
    # 戻り値    なし
    #========================================
    def OnOK(self):
        error_string = ctypes.create_string_buffer(256)    # エラーコード文字列
        lret = ctypes.c_long()                             # 戻り値取得用
        ch_no = ctypes.c_short()                           # チャネルナンバー
        pulse_width = ctypes.c_short()                     # パルス幅

        #----------------------------------------
        # 画面から設定値取得
        #----------------------------------------
        for i in range(0, 8):
            buf = self.textbox_counter_value_var[i].get()
            if self.ui.radiobutton_counter_value_base_var.get() == 1:
                #----------------------------------------
                # 入力値が数値かどうかをチェック
                #----------------------------------------
                if False == self.isnum(buf, 10):
                    self.ui.show_error("Error", "入力値が無効です。")
                    return
                else:
                    self.compare_value[i] = ctypes.c_ulong(int(buf))
            else:
                #----------------------------------------
                # 入力値が数値かどうかをチェック
                #----------------------------------------
                if False == self.isnum(buf, 16):
                    self.ui.show_error("Error", "入力値が無効です。")
                    return
                else:
                    self.compare_value[i] = ctypes.c_ulong(int(buf, 16))
        pulse_width.value = self.ui.combobox_count_match_pulse.current()
        #----------------------------------------
        # 画面の最後の設定値を記録
        #----------------------------------------
        self.parent.compare_window_textbox_ch0_last_edit = self.ui.textbox_ch0_value_var.get()
        self.parent.compare_window_textbox_ch1_last_edit = self.ui.textbox_ch1_value_var.get()
        self.parent.compare_window_textbox_ch2_last_edit = self.ui.textbox_ch2_value_var.get()
        self.parent.compare_window_textbox_ch3_last_edit = self.ui.textbox_ch3_value_var.get()
        self.parent.compare_window_textbox_ch4_last_edit = self.ui.textbox_ch4_value_var.get()
        self.parent.compare_window_textbox_ch5_last_edit = self.ui.textbox_ch5_value_var.get()
        self.parent.compare_window_textbox_ch6_last_edit = self.ui.textbox_ch6_value_var.get()
        self.parent.compare_window_textbox_ch7_last_edit = self.ui.textbox_ch7_value_var.get()
        self.parent.compare_window_radiobutton_counter_value_base_var = self.ui.radiobutton_counter_value_base_var.get()
        #----------------------------------------
        # 各チャネル毎に
        #----------------------------------------
        for ch_no.value in range(0, self.parent.channel_num.value):
            #----------------------------------------
            # 比較値設定
            #----------------------------------------
            lret.value = ccnt.CntNotifyCountUp(self.parent.id, ch_no, 0, self.compare_value[ch_no.value], 0)
            #-----------------------------
            # エラー処理
            #-----------------------------
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                text_buf = f"CntNotifyCountUp = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # パルス長設定
            #----------------------------------------
            lret.value = ccnt.CntSetPulseWidth(self.parent.id, ch_no, pulse_width)
            #-----------------------------
            # エラー処理
            #-----------------------------
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                text_buf = f"CntSetPulseWidth = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
        #----------------------------------------
        # ウィンドウを終了する
        #----------------------------------------
        self.ui.compare_window.destroy()

    #========================================
    # 関数名    OnClickedButtonCancel
    # 引数      なし
    # 詳細      Cancelボタンクリックイベント関数
    # 戻り値    なし
    #========================================
    def OnClickedButtonCancel(self):
        #----------------------------------------
        # ウィンドウを終了する
        #----------------------------------------
        self.ui.compare_window.destroy()