# -*- coding: UTF-8 -*-

from common.constant import PATCH_TYPE, PATCH_EVALU

import java.lang.Exception as JException


CMD_DEFAULT_TIMEOUT = 60
UPD_CHECK_STATUS_DICT = {
            # 界面展示 0等待检查, 1正在检查, 2警告, 3通过, 4不通过， 5忽略
            "0": 0,  # 等待执行
            "1": 1,  # 执行中
            "2": 3,  # 执行成功
            "3": 4,  # 执行失败
            "4": 4,  # 执行错误
            "5": 5,  # 忽略
        }

# 补丁评估场景不需要显示的检查项
NOT_UPDATE_ITEM = "HotpatchCheck"

def getNotPassedItemsMsg(checkItems):
    errMsg = ""
    for item in checkItems:
        itemState = item.get("status")
        if 4 == itemState:
            ctrl = item.get("ctrl", "")
            name = item.get("name", "")
            suggestion = item.get("suggession", "")
            errMsg += "["+name+"]"+"\n"+suggestion+"\n"
    return errMsg

class CheckItemObserver():
    def __init__(self, dataDict, checkType):
        self.dataDict = dataDict
        self.logger = self.dataDict.get("logger")
        self.allCheckItems = []
        self.checkType = checkType #precheck or postcheck
        self.dev = self.dataDict.get('dev')
        self.match_type = self.dev.getMatchType()

    def setProgress(self, progress):
        try:
            self.logger.info("setProgress is start")
            observer = self.dataDict.get("progressObserver")
            if observer != None:
                self.logger.info("progress" + str(progress))
                observer.updateItemProgress(self.dataDict.get("dev"), int(progress), "", self.checkType)
        except (JException, Exception), exption:
            self.logger.error("setProgress is error")
            pass

    def toUiStatus(self, status):
        return UPD_CHECK_STATUS_DICT.get(status, 0)

    def postMsg(self, check_items):
        self.allCheckItems = check_items
        self.__update_checkitems_4_evalu()

    def __update_checkitems_4_evalu(self):
        if self.match_type != PATCH_EVALU:
            return

        for item in self.allCheckItems[:]:
            if item.get("nameId", "") in NOT_UPDATE_ITEM:
                self.allCheckItems.remove(item)
        observer = self.dataDict.get("progressObserver")
        observer.updateCheckItems(self.dataDict.get("dev"),
                                  self.allCheckItems)

    def getAllCheckItems(self):
        return self.allCheckItems

    def isAllSystemInnerItemsPassed(self):
        for item in self.allCheckItems:
            itemState = item.get("status")
            if 4 == itemState:
                # 设备列表中的操作仅支持重试，单个检查项可支持忽略
                return False
        return True

