# -*- coding: UTF-8 -*-
from common.baseFactory import *
from common import resourceParse 
from common.baseFactory import log
from frame.rest.restUtil import Tlv2Rest
from frame.rest import restData


def execute(dataDict):

    ##执行升级后检查
    return postCheck(dataDict)

def disposeRecs(recs, dataDict):
    lang = dataDict['lang']
    resource = resourceParse.execute(lang)
    log.info(dataDict, "resource:" + str(resource))
    recNum = recs.size()
    log.info(dataDict, "XnetOperationModeCheck recs:" + str(recs))
    
    checkMsgTitle = resource.get("XnetOperationModeCheck.title") + '\n'
    upgradeErrMsg = ''
    itemState = True
    for index in range(0, recNum):
        rec = recs.get(index)
        nodeId = Tlv2Rest.getRecordValue(rec, restData.Upgrade.RecordParam.RECORD_NODE_ID)
        result = Tlv2Rest.getRecordValue(rec, restData.Upgrade.RecordParam.RECORD_RESULT)
        log.info(dataDict, "XnetOperationModeCheck result:" + result)
        if result == "TimeOut":
            #执行超时
            itemState = False
            errorKey = "XnetOperationModeCheck.timeout"
        elif result == "NotPass":
            #检查不通过
            itemState = False
            errorKey = "XnetOperationModeCheck.notpass"
        elif result == "Pass":
            #检查通过
            errorKey = "XnetOperationModeCheck.pass"
        else:
            #检查异常
            itemState = False
            errorKey = "XnetOperationModeCheck.error"
        upgradeErrMsg += getUpgErrMsg(resource, nodeId, errorKey)
    if not upgradeErrMsg:
        itemState = False
        upgradeErrMsg = resource.get("XnetOperationModeCheck.error")
    upgradeErrMsg = checkMsgTitle + upgradeErrMsg
    return (itemState, upgradeErrMsg, None)

def postCheck(dataDict):
    
    #设备是否需要检查
    if not isDevNeedCheck(dataDict):
        log.info(dataDict, "Do not need to check XNET configuration!")
        return (True, "", None)

    recs = execute_check_retry(dataDict, "xnetpal setnapisch", 2)
    return disposeRecs(recs, dataDict)

def _isHighEndDevice(devType):

    if devType.strip().startswith("18") or devType.strip().startswith("HVS"):
        return True
    return False

def isDevNeedCheck(dataDict):

    dev = dataDict.get('dev')
    devType = str(dev.getDeviceType())
    productVersion = dev.getProductVersion()
    log.info(dataDict, "Device type is:" + devType)
    log.info(dataDict, "Product version is:" + productVersion)
    #非高端的不需要处理(Dorado18000不需要检查)
    if not _isHighEndDevice(devType):
        return False
    #V5R7C10&V3R6C20及以后版本需要检查
    if productVersion < "V300R006C20":
            return False
    elif productVersion.startswith("V500") and productVersion < "V500R007C10":
            return False

    return True
