#!/usr/bin/env python
# -*- encoding: utf-8 -*-


from ui.protect import Protect
from ui.own.frame_theme import MyFrame
from ui.own.my_chart_view import MyChartView
from utils.globalvar import SD
from utils.qt import QMessageBox, QChart, QValueAxis, QHBoxLayout, QPainter, Qt, Signal, Slot, QLegendMarker


class Win_Protect(Protect, MyFrame):

    # 信号传递
    on_read_param_signal = Signal()
    on_write_param_signal = Signal()
    on_exit_param_signal = Signal()

    def __init__(self, parent=None):
        super(Win_Protect, self).__init__(parent)
        self.setupUi(self)

        self.btn_read_param.clicked.connect(self.on_btn_read_param)
        self.btn_write_param.clicked.connect(self.on_btn_write_param)
        self.btn_exit_param.clicked.connect(self.on_btn_exit_param)
        self.protect_table.itemClicked.connect(self._param_item_clicked)
        self.qline_data_set.returnPressed.connect(self._protect_data_changed)


    def on_btn_read_param(self):
        self.on_read_param_signal.emit()


    def on_btn_write_param(self):
        self.on_write_param_signal.emit()

    def on_btn_exit_param(self):
        self.on_exit_param_signal.emit()

    def _protect_data_changed(self):
        value = (float(self.qline_data_set.text()) - float(self.qline_offset.text()))/float(self.qline_fbl.text())
        self.qline_data.setText(str(value))


    def _param_item_clicked(self, index):
        self.qline_name.setText(self.protect_table.item(index.row(), 0).text())
        self.qline_addr.setText(self.protect_table.item(index.row(), 3).text())
        self.qline_data_long.setText(self.protect_table.item(index.row(), 5).text())
        self.qline_fbl.setText(self.protect_table.item(index.row(), 6).text())
        self.qline_offset.setText(self.protect_table.item(index.row(), 7).text())
        self.qline_dw.setText(self.protect_table.item(index.row(), 2).text())
        self.qline_data.setText(self.protect_table.item(index.row(), 8).text())
        self.qline_data_set.setText(self.protect_table.item(index.row(), 1).text())


    def set_error(self):
        QMessageBox.critical(self, "错误" if SD.SYSTEM_LANGUAGE == 0 else "Error", "参数无效！" if SD.SYSTEM_LANGUAGE == 0 else "Param Error！")

    def can_connect_error(self):
        QMessageBox.critical(self, "连接状态" if SD.SYSTEM_LANGUAGE == 0 else "Connect State", "CAN 连接失败！" if SD.SYSTEM_LANGUAGE == 0 else "CAN Connect Error！")
