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


from utils.globalvar import SD
from widget.bms_protect import Win_Protect


class BmsProtectControll:
    def __init__(self):
        self._view = Win_Protect()
        self.i = 0
        self.init()

    def init(self):
        self._view.on_read_param_signal.connect(self._read_param)
        self._view.on_write_param_signal.connect(self._write_param)
        self._view.on_exit_param_signal.connect(self._exit_param)
        

    def _read_param(self):
        try:
            data = []
            if len(data) < 8:
                data += (8 - len(data)) * [0]
            data[0] = 0xFF
            data[1] = 0xFF
            data[2] = 0xBB
            data[6] = self.i
            self.i = self.i + 1
            if self.i == 255:
                self.i = 0
            data[7] = data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6]
            msg = SD.CAN_CONTROL.send((0x18 << 24) | (SD.BCU_ID << 16) | 0x1801, data)
            data[0] = 1
            data[2] = 0
            data[6] = self.i
            self.i = self.i + 1
            if self.i == 255:
                self.i = 0
            data[7] = data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6]
            msg = SD.CAN_CONTROL.send((0x18 << 24) | (SD.BCU_ID << 16) | 0x1801, data)
        except:
            self._view.can_connect_error()

    def _write_param(self):
        try:
            data = []
            if len(data) < 8:
                data += (8 - len(data)) * [0]
            data[0] = int(self._view.qline_addr.text(), 16) & 0xFF
            data[1] = int(self._view.qline_addr.text(), 16) >> 8
            data[2] = int(float(self._view.qline_data.text())) & 0xFF
            data[3] = int(float(self._view.qline_data.text())) >> 8 
            msg = SD.CAN_CONTROL.send((0x18 << 24) | (SD.BCU_ID << 16) | 0x1802, data)
        except ValueError:
            self._view.set_error()
        except:
            self._view.can_connect_error()


    def _exit_param(self):
        try:
            data = []
            if len(data) < 8:
                data += (8 - len(data)) * [0]
            data[0] = 3
            data[1] = 0xFF
            data[6] = self.i
            self.i = self.i + 1
            if self.i == 255:
                self.i = 0
            data[7] = data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6]
            msg = SD.CAN_CONTROL.send((0x18 << 24) | (SD.BCU_ID << 16) | 0x1801, data)
        except:
            self._view.can_connect_error()
