#================================================================
#================================================================
# API-CNT(WDM) for サンプリング機能搭載デバイス
# カウンタサンプル
# 通知設定ファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ccnt
from NotifyUI import NotifyWindowUI


#========================================
# NotifyWindow クラス
#========================================
class NotifyWindow:
    #========================================
    # 初期化関数
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # マクロ定義
        #----------------------------------------
        self.CHANNEL_NUM = 4                                           # 最大チャンネル数
        #----------------------------------------
        # 変数
        #----------------------------------------
        self.textbox_count_reg0_value_var = [None] * self.CHANNEL_NUM  # 比較レジスタ0コントロール変数格納用の配列
        self.textbox_count_reg0_value = [None] * self.CHANNEL_NUM      # 比較レジスタ0コントロール格納用の配列
        self.textbox_count_reg1_value_var = [None] * self.CHANNEL_NUM  # 比較レジスタ1コントロール変数格納用の配列
        self.textbox_count_reg1_value = [None] * self.CHANNEL_NUM      # 比較レジスタ1コントロール格納用の配列
        #----------------------------------------
        # 親ウィンドウの設定
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # UIの作成を開始
        #----------------------------------------
        self.ui = NotifyWindowUI(parent)
        #----------------------------------------
        # テキストボックスの比較レジスタ0の値とインスタンス配列を設定する
        #----------------------------------------
        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
        #----------------------------------------
        # テキストボックスの比較レジスタ1の値とインスタンス配列を設定する
        #----------------------------------------
        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
        #----------------------------------------
        # UIコントロールのコールバック関数を設定
        #----------------------------------------
        self.ui.setup_commands(
            command_notify_window_ok = self.OnOK,
            command_notify_window_cancel = self.OnClickedButtonCancel
        )
        #----------------------------------------
        # UIの更新を開始
        #----------------------------------------
        self._update_ui()

    #========================================
    # UIの更新関数
    #========================================
    def _update_ui(self):
        ch_no = ctypes.c_short()   # チャネルナンバー

        #----------------------------------------
        # ウィンドウ画面は最後に選択した設定に設定されます
        #----------------------------------------
        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)
        #----------------------------------------
        # デバイスに存在しないチャネル用コントロールを無効化
        #----------------------------------------
        for ch_no.value in range(self.CHANNEL_NUM):
            #----------------------------------------
            # 総チャネル数を超えた場合表示を無効化
            #----------------------------------------
            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')
            #----------------------------------------
            # 総チャネル数以下の場合表示を有効化
            #----------------------------------------
            else:
                self.textbox_count_reg0_value[ch_no.value].config(state = 'normal')
                self.textbox_count_reg1_value[ch_no.value].config(state = 'normal')

    #========================================
    # 関数名    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

    #========================================
    # 関数名    OnOK()
    # 引数      なし
    # 詳細      設定完了処理
    # 戻り値    なし
    #========================================
    def OnOK(self):
        error_string = ctypes.create_string_buffer(256)    # エラーコード文字列
        lret = ctypes.c_long()                             # 戻り値取得用
        ch_no = ctypes.c_short()                           # チャネルナンバー
        reg_no = ctypes.c_short()                          # レジスタナンバー
        comp_data_type1 = ctypes.c_ulong * 4               # 比較値タイプ1
        comp_data_type2 = comp_data_type1 * 4              # 比較値タイプ2
        comp_data = comp_data_type2()                      # 比較値

        #----------------------------------------
        # 設定情報の取得
        #----------------------------------------
        for ch_no.value in range(self.parent.channel_num.value):
            #--------------------
            # REG0の値を取得
            #--------------------
            buf = self.textbox_count_reg0_value_var[ch_no.value].get()
            #--------------------
            # 入力値が数値かどうかをチェック
            #--------------------
            if False == self.isnum(buf, 10):
                self.ui.show_error("Error", "入力値が無効です。")
                return
            else:
                comp_data[ch_no.value][0] = ctypes.c_ulong(int(buf))
            #--------------------
            # REG1の値を取得
            #--------------------
            buf = self.textbox_count_reg1_value_var[ch_no.value].get()
            #--------------------
            # 入力値が数値かどうかをチェック
            #--------------------
            if False == self.isnum(buf, 10):
                self.ui.show_error("Error", "入力値が無効です。")
                return
            else:
                comp_data[ch_no.value][1] = ctypes.c_ulong(int(buf))
            #--------------------
            # 画面の最後の設定値を記録
            #--------------------
            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()

        #----------------------------------------
        # 画面の最後の設定値を記録
        #----------------------------------------
        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()
        #----------------------------------------
        # 設定情報をデバイスへセット
        #----------------------------------------
        for ch_no.value in range(0, self.parent.channel_num.value):
            for reg_no.value in range(0, 2):
                #----------------------------------------
                # カウント一致の通知 & 比較レジスタ 設定
                #----------------------------------------
                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)
                    #----------------------------------------
                    # メッセージ表示
                    #----------------------------------------
                    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:
            #----------------------------------------
            # カウンタエラー通知 設定
            #----------------------------------------
            lret.value = ccnt.CntNotifyCounterError(self.parent.id, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                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:
            #----------------------------------------
            # キャリー/ボロー通知 設定
            #----------------------------------------
            lret.value = ccnt.CntNotifyCarryBorrow(self.parent.id, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                text_buf = f"CntNotifyCarryBorrow = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        #----------------------------------------
        # ウィンドウを終了する
        #----------------------------------------
        self.ui.notify_window.destroy()

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