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

import re
import string
import os
from defusedxml import ElementTree
from constant import ProductModelType
from common.baseFactory import log
from cbb.frame.util import public_ip_address_utils

HOTPATCH_XMLFILE = r"..{0}..{0}conf{0}hotPatchInfo.xml".format(os.sep)

GLOBAL_DES_SEPARATE_LINE = "==================================================\n"

# *************************************************************#
# 函数名称: getHotPatchCheckInfo
# 功能说明: 整合所有需要显示的信息
# 其 他   :  hotPatchSearchCode, hotPatchDesInfo, lang
# *************************************************************#
def getHotPatchCheckInfo(hotPatchSearchCode, hotPatchDesInfo,devType, lang, dataDict):
    
    #初始化变量
    hotPatchSearchInfo = ""
    hotPatchDescInfo = ""
    hotPatchCheckDisplayInfo = ""
    
    hotPatchDir = ""
    hotPatchFileName = ""
    #将补丁解决问题的描述信息加上分隔符
    hotPatchDesInfo = GLOBAL_DES_SEPARATE_LINE + hotPatchDesInfo + GLOBAL_DES_SEPARATE_LINE
    
    hotPatchFileName = hotPatchSearchCode.split()[-1]
    hotPatchDir = hotPatchSearchCode.replace(hotPatchFileName, "").strip()
    support_website = public_ip_address_utils.get_support_enterprise_website()
    if lang == "zh":
        hotPatchDescInfo += u"\n【热补丁检查结果】\n"
        hotPatchDescInfo += u"请安装热补丁" + hotPatchSearchCode + u",补丁描述如下：\n" + hotPatchDesInfo
        hotPatchSearchInfo += u"\n【热补丁包下载说明】\n（1）请登录网站“{}”。\n".format(
            support_website)
        if devType == 'T':
            hotPatchSearchInfo += u"（2）登录成功后，进入如下路径： 软件下载 > IT > 存储 > 统一存储 > 入门级存储\n"
        elif devType == 'V3':
            hotPatchSearchInfo += u"（2）登录成功后，进入如下路径： 软件下载 > IT > 存储 > 统一存储 >中端存储\n"
        elif devType == '18000':
            hotPatchSearchInfo += u"（2）登录成功后，进入如下路径： 软件下载 > IT > 存储 > 磁盘存储 > OceanStor 18000系列高端存储\n"
        else:
            hotPatchSearchInfo += u"（2）登录成功后，进入如下路径： 软件下载 > IT > 存储 > 磁盘存储 \n"
        hotPatchSearchInfo += u"（3）选择" + hotPatchDir + u"，下载热补丁包：" + hotPatchFileName + u"。\n"
        hotPatchSearchInfo += u"（4）如有任何问题，请联系技术支持工程师。"
    else:
        hotPatchDescInfo += u"\n[HotPatch Check Result]\n"
        hotPatchDescInfo += u"Please install the hotpatch:" + hotPatchSearchCode + u",the details of hot patch as following:\n" + hotPatchDesInfo
        hotPatchSearchInfo += u"\n[HotPatch Download Note]\n(1) Log in to \"{}\".\n".format(
            support_website)
        if devType == 'T':
            hotPatchSearchInfo += u"(2) After you log in, access Downloads > IT > Storage > Unified Storage > Entry Lecel Storage.\n"
        elif devType == 'V3':
            hotPatchSearchInfo += u"(2) After you log in, access Downloads > IT > Storage > Unified Storage > Midrange Storage\n"
        elif devType == '18000':
            hotPatchSearchInfo += u"(2) After you log in, access Downloads > IT > Storage > Disk Storage > OceanStor 18000 enterprise Storage.\n"
        else:
            hotPatchSearchInfo += u"(2) After you log in, access Downloads > IT > Storage > Disk Storage.\n"
        hotPatchSearchInfo += u"(3) Choose " + hotPatchDir + ", then download the hotpatch package:" + hotPatchFileName + u".\n"
        hotPatchSearchInfo += u"(4) If you have any questions, please contact the engineer."
    #整体显示信息整合
    hotPatchCheckDisplayInfo = hotPatchDescInfo + hotPatchSearchInfo
    log.info(dataDict,'Get hot patch check info succeed !')
    return hotPatchCheckDisplayInfo

# *************************************************************#
# 函数名称: execute
# 功能说明: 解析热补丁配套表，查询指定版本的热补丁信息
# 其 他   :  无
# *************************************************************#
def checkPatchInfo(DeviceType, SystemVersion, lang, dataDict):

    #初始化返回信息
    isExistHotPatch = False
    hotPatchVer = ""
    allDisplayCheckInfo = ""
    hotPatchDesInfo = ""
    
    #入参检查：设备型号和系统版本不能为空
    if DeviceType == "" or SystemVersion == "":
        return (isExistHotPatch, hotPatchVer, allDisplayCheckInfo)
    
    productVer = SystemVersion[0:8]
    
    #加载XML文件（加载指定文件）
    scriptPath = os.path.split(os.path.realpath(__file__))[0]
    filepath = scriptPath + os.sep + HOTPATCH_XMLFILE
    root = ElementTree.parse(filepath)
    
    #获取所有的element
    nodeList = root.getiterator("Product")
    
    #获取指定R版本节点信息
    productNode = None
    for node in nodeList:
        if node.attrib["Version"] == productVer:
            productNode = node
            break
        else:
            continue

    #当前产品不存在节点，直接返回不需要热补丁
    if productNode == None:
        return (isExistHotPatch, hotPatchVer, allDisplayCheckInfo)
    
    #获取指定产品节点的子节点信息
    for hotPatchNode in  productNode.getchildren():
        
        #初始化配置信息
        hotPatchDeviceTypeListStr = ""
        hotPatchDeviceTypeList = []
        hotPatchSysSpcVersion = ""
        hotPatchVersion = ""
        hotPatchInfoZh = ""
        hotPatchInfoEn = ""
        hotPatchSearchCode = ""

        #查询每个热补丁节点的配置数据
        for detailInfo in hotPatchNode.getchildren(): 
            #设备类型列表
            if detailInfo.tag == "DeviceType":
                hotPatchDeviceTypeListStr = str(detailInfo.text)
                #创建补丁支持设备型号的列表
                hotPatchDeviceTypeList = hotPatchDeviceTypeListStr.replace(" ", "").split(",")
            #补丁配套的SPC版本号
            elif detailInfo.tag == "SysSpcVersion":
                hotPatchSysSpcVersion = str(detailInfo.text)
            #热补丁版本号
            elif detailInfo.tag == "HotPatchVersion":
                hotPatchVersion = str(detailInfo.text)
            #补丁中文描述
            elif detailInfo.tag == "DesZh":
                for desZhItem in detailInfo:
                    hotPatchInfoZh += desZhItem.text + "\n"
            #补丁英文描述   
            elif detailInfo.tag == "DesEn":
                for desEnItem in detailInfo:
                    hotPatchInfoEn += desEnItem.text + "\n"
            #补丁搜索字符
            elif detailInfo.tag == "SearchCode":
                hotPatchSearchCode = str(detailInfo.text)
            else:
                continue
            
        #指定设备型号和系统版本号，检索是否匹配
        if DeviceType in hotPatchDeviceTypeList and hotPatchSysSpcVersion == SystemVersion:
            isExistHotPatch = True
            hotPatchVer = hotPatchSearchCode
            log.info(dataDict,"Search for the hotpatch version succeed:" + hotPatchVer)
            if lang == "zh":
                hotPatchDesInfo = hotPatchInfoZh
            else:
                hotPatchDesInfo = hotPatchInfoEn
            #一个系统版本只对应一个热补丁
            break
    devType = ProductModelType.typeMap.get(DeviceType)
    log.info(dataDict,"devType: %s"%devType)
    #补丁描述信息不为空
    if hotPatchDesInfo != "":
        #根据设备型号整合所有的显示信息
        allDisplayCheckInfo = getHotPatchCheckInfo(hotPatchSearchCode, hotPatchDesInfo,devType, lang, dataDict)
        
    return (isExistHotPatch, hotPatchVer, allDisplayCheckInfo)

# *************************************************************#
# 函数名称: getVersionMap
# 功能说明: 解析热补丁配套表，获取所有版本的配套关系
# 其 他   :  无
# *************************************************************#
def getVersionMap(dataDict):

    #热补丁版本号+系统SPC版本号对应关系
    VersionStr = ""
    VersionMap = {}
    
    #加载XML文件（加载指定文件）
    scriptPath = os.path.split(os.path.realpath(__file__))[0]
    filepath = scriptPath + os.sep + HOTPATCH_XMLFILE
    root = ElementTree.parse(filepath)
    
    #获取所有的element
    productNodeList = root.getiterator("Product")

    #获取指定产品节点的子节点信息
    for productNode in productNodeList:
        hotPatchList = productNode.getchildren()
        
        for hotPatchNode in hotPatchList:
            
            #初始化配置信息
            hotPatchDeviceTypeListStr = ""
            hotPatchSysSpcVersion = ""
            hotPatchVersion = ""
            SysVersionSupported = ""
            hotPatchSearchCode = ""
            
            #查询每个热补丁节点的配置数据
            for detailInfo in hotPatchNode.getchildren(): 

                #设备类型列表
                if detailInfo.tag == "DeviceType":
                    hotPatchDeviceTypeListStr = str(detailInfo.text)
                #补丁配套的SPC版本号
                elif detailInfo.tag == "SysSpcVersion":
                    hotPatchSysSpcVersion = str(detailInfo.text)
                #热补丁版本号
                elif detailInfo.tag == "HotPatchVersion":
                    hotPatchVersion = str(detailInfo.text)
                #热补丁配套的系统版本
                elif detailInfo.tag == "SysVersionSupported":
                    SysVersionSupported = str(detailInfo.text)
                #补丁搜索字符
                elif detailInfo.tag == "SearchCode":
                    hotPatchSearchCode = str(detailInfo.text)
                else:
                    continue

            #获取xml文件中所有版本的配套关系
            #key值：searchCode：OceanStor S2900 V100R002C01SPHh01
            MapKey0 = hotPatchSearchCode
            #value0：补丁支持的设备类型列表：S2200T,S2200T-S,S2600T,S2900
            MapValue0 = hotPatchDeviceTypeListStr
            #value1：补丁配套的系统SPC版本号：V100R002C01SPCh00
            MapValue1 = hotPatchSysSpcVersion
            #value2：补丁配套的系统内部版本号：1100221511
            MapValue2 = SysVersionSupported

            VersionStr = MapValue0 + "=" + MapValue1 + "=" + MapValue2
            #保存到字典
            VersionMap[MapKey0] = VersionStr
    log.info(dataDict,'Get version map succeed !')
    #返回所有版本配套关系
    return VersionMap

