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

import re
import os
import shutil

from common import resourceParse
from common import getPatchInXml
from common.constant import PATCH_TYPE
from common.baseFactory import log
from cbb.frame.util.tar_util import decompress_tar_special_file


# *************************************************************#
# 函数名称: decompressionUpgradePKG
# 功能说明: 解压热补丁包的配置文件(需要支持普通热补丁包和特殊热补丁包)
# 其 他   :  无
# *************************************************************#  
def decompressionUpgradePKG(filePath):
    
    extractPath = filePath[0: filePath.index('.tgz')]
    # 普通热补丁包：patch.conf文件在第一层压缩目录下
    return decompress_tar_special_file(filePath, extractPath, 'patch.conf')


# *************************************************************#
# 函数名称: getCurrentHotPatchInfo
# 功能说明: 获取每一个热补丁包对应关系：热补丁版本号+热补丁包文件名
# 其 他   :  无
# *************************************************************#  
def getCurrentHotPatchInfo(dataDict,hotPatchName, VersionMap):

    #热补丁字典信息：补丁版本号+热补丁文件名
    hotPatchInfo = {"Version": "", "FilePath": ""}
    hotPatchInfoList = []

    sysVersion = ""
    confiHotPatchVer = ""
    versionValue = ""
    totalHotPatchVersion = ""
    totalHotPatchVersionList = []
    vaildPkgFlag = False
    
    extractPath = hotPatchName[0:-4]

    #由调用者保证.tgz格式的热补丁升级包
    if hotPatchName[-4:] != ".tgz":
        return None
    conFileFd = None
    try:
        #解压.tgz升级包文件，提取patch.conf文件
        iRet = decompressionUpgradePKG(hotPatchName)
        if True == iRet:
            #热补丁包：解析patch.conf文件
            confFile = extractPath + os.sep + 'patch.conf'
            conFileFd = open(confFile, "r")
            confInfo = conFileFd.read()
            #关闭文件句柄
            conFileFd.close()
            lineList = confInfo.splitlines()
            
            for line in lineList:
                field = line.split()
                if len(field) < 2:
                    continue
                #获取配置文件中的热补丁版本号
                if field[0] == "Version":
                    confiHotPatchVer = field[1]
                #获取基础版本号
                if field[0] == "SysVersionSupported":
                     sysVersion = field[1]
                if confiHotPatchVer != "" and sysVersion != "":
                    #通过系统版本号1180211301来匹配versionMap信息
                    for key in VersionMap:
                        versionValue = VersionMap[key]

                        if re.search(sysVersion, versionValue, re.IGNORECASE):
                                #热补丁完整版本号:S5600T V100R002C00SPHc01
                            totalHotPatchVersion = key
                                #校验热补丁版本号
                            if re.search(confiHotPatchVer, key, re.IGNORECASE):
                                vaildPkgFlag = True
                                totalHotPatchVersionList.append(totalHotPatchVersion)
                        else:
                            continue
                    break
                else:
                    continue
            
    except Exception, e:
        pass
    finally:
        if conFileFd != None:
            conFileFd.close()
        shutil.rmtree(hotPatchName[0:-4], ignore_errors=True)

    #设置热补丁信息
    if True == vaildPkgFlag:
        for tempInfo in totalHotPatchVersionList:
            #每次循环均初始化
            hotPatchInfo = {"Version": "", "FilePath": ""}
        
            hotPatchInfo["FilePath"] = hotPatchName
            hotPatchInfo["Version"] = tempInfo
            hotPatchInfoList.append(hotPatchInfo)

        return hotPatchInfoList
    else:
        return None

# *************************************************************#
# 函数名称: execute
# 功能说明: 解析热补丁包所在路径，返回字典：热补丁版本号+对应的文件名(入口函数)
# 其 他   :  无
# *************************************************************#
def execute(dataDict):
    #热补丁字典信息：补丁版本号+热补丁文件名
    hotPatchInfo = {"Version": "", "FilePath": ""}
    hotPatchInfoList = []
    context = dataDict.get('context')
    deviceSN = str(dataDict.get('dev').getDeviceSerialNumber())
    context["patchType_%s"%deviceSN] = PATCH_TYPE.HOT_PATCH
    
    #解析结果
    parseResults = {}
    #有效的热补丁包列表
    hotPatchFiles = []
    #解析结果
    parseFlag = True
    errMsg = ""

    lang = dataDict.get("lang")
    path = dataDict.get("parsePath")
    fileFlag = os.path.isfile(path)
    
    #解析resource文件并保存
    resource = resourceParse.execute(lang)
    dataDict["resource"] = resource
    specialPkgFlag = False
    
    #从xml文件中获取版本配套关系并保存
    VersionMap = {}
    iRet = getPatchInXml.getVersionMap(dataDict)
    VersionMap = iRet

    """获取传入Path中的所有热补丁包名List"""
    #如果传入的是文件的绝对路径
    if True == fileFlag:
        fileName = path
        #传入的只能为.tgz的压缩包
        if fileName[-4:] == ".tgz":
            hotPatchFiles.append(fileName)
    #如果传入的是文件夹的绝对路径
    else:
        files = os.listdir(path)
        for file in files:
            #热补丁升级包必须为.tgz格式
            if file[-4:] == ".tgz":
                hotPatchFiles.append(path + os.sep + file)
    
    #解析所有的热补丁升级包，将升级包版本号与文件名对应
    for tgzFileName in hotPatchFiles:
        iRet = getCurrentHotPatchInfo(dataDict,tgzFileName, VersionMap)
        if iRet != None:
            hotPatchInfoList = iRet
            for hotPatchInfo in hotPatchInfoList:
                log.info(dataDict,'Version:%s  FilePath:%s'%(hotPatchInfo["Version"],hotPatchInfo["FilePath"]))
                parseResults[hotPatchInfo["Version"]] = hotPatchInfo["FilePath"]

    #如果解析结果为空，则返回False
    if parseResults == {}:
        parseFlag = False
        errMsg = resource.get("upload.pkgPathInexistValidPkg")
    
    log.info(dataDict,'File patch parse succeed !')
    return (parseFlag, errMsg, parseResults)
