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


import csv
from utils.globalvar import SD
from widget.bms_record import Win_Record
from model.record_model import RecordModel


class BmsRecordControll:
    def __init__(self):
        self._view = Win_Record()
        self._model = RecordModel()
        self.init()

    def init(self):
        self._view.can_record_start_signal.connect(self._save)
        self._view.can_record_stop_signal.connect(self._stop)
        
    def _save(self):
        SD.RECORD_NAME, ok = self._view.save_csv()
        if SD.RECORD_NAME == "":
            return
        self._view.save_record.setDisabled(True)
        self._view.stop_record.setDisabled(False)
        header =  ["时间戳", "簇号", "故障等级", "簇电压", "簇电流", "簇SOC", "簇SOH", "簇单体V平均", "簇单体Vmax单体号", "簇单体Vmax", "簇单体Vmin单体号", "簇单体Vmin", "簇单体T平均", "簇单体Tmax单体号", "簇单体Tmax", "簇单体Tmin单体号", "簇单体Tmin", "主正接触器", "主负接触器", "预充接触器", "断路器", "干接点1", "干接点2", "最高单体SOC", "最低单体SOC", "平均单体SOC"]
        if SD.CCU_TYPE == 0:
            header_1=  ["V" + str(i + 1) for i in range(16)]
            header_2 =  ["T" + str(i + 1) for i in range(16)]
        else:
            header_1=  ["V" + str(i + 1) for i in range(396)]
            header_2 =  ["T" + str(i + 1) for i in range(360)]            
        header.extend(header_1)
        header.extend(header_2)
        if ok:
            with open(SD.RECORD_NAME, 'w') as csvfile:
                writer = csv.writer(csvfile, dialect='excel', lineterminator='\n')
                writer.writerow(header)
                SD.RECORD_SAVE = 1
        else:
            return

    def _stop(self):
        self._view.save_record.setDisabled(False)
        self._view.stop_record.setDisabled(True)
        SD.RECORD_SAVE = 0
