# -*- coding: UTF-8 -*-
import re
from resource.resource import MESSAGES_DICT
from cbb.frame.cli import cliUtil
from cbb.frame.context import contextUtil
from cbb.frame.base import baseUtil


def execute(data_dict):
    """
    :功能描述: 电源升级admin超级管理员检查
    """

    check_item = CheckAdminToPowerUpgrade(data_dict)
    result = check_item.execute()
    if result:
        return True, "", "\n".join(check_item.origin_info)
    return False, "\n".join(check_item.msg_list), "\n".join(check_item.origin_info)


class CheckAdminToPowerUpgrade:
    def __init__(self, data_dict):
        self.data_dict = data_dict
        self.cli = contextUtil.getCli(data_dict)
        self.logger = contextUtil.getLogger(data_dict)
        self.lang = contextUtil.getLang(data_dict)
        self.dev = self.data_dict.get("dev")
        self.origin_info = []
        self.msg_list = []

    def execute(self):
        patch_version_dict = {'6.0.1': 'SPH33', '6.1.0': 'SPH27', '6.1.2': 'SPH30'}
        _, software_version, hotpatch_version, _ = cliUtil.get_system_version_with_ret(self.cli, self.lang)
        pkgpatch_version = self.data_dict.get("pkgVersion")
        log_info = "software version: {}, hotpatch version: {}, pkgpatch version: {}" \
                   .format(software_version, hotpatch_version, pkgpatch_version)
        self.origin_info.append(log_info)
        self.logger.info(log_info)
        if software_version not in patch_version_dict: # 非目标版本
            return True
        if compare_patch_version(pkgpatch_version, patch_version_dict.get(software_version)) != 0:
            return True
        _, cli_ret, _ = cliUtil.execCmdInCliMode(self.cli, "show user", True, self.lang)
        ret_user_dict = cliUtil.getHorizontalCliRet(cli_ret)
        self.origin_info.append(cli_ret)
        for user_info in ret_user_dict:
            if user_info.get("Name") == "admin" and user_info.get("Role ID") == "1":
                return True
        self.msg_list.append(self.get_msg("power.patch.upgrade.admin"))
        return False

    def get_msg(self, msg_key):
        return baseUtil.getPyResource(self.lang, msg_key, "", resource=MESSAGES_DICT)


def compare_patch_version(version1, version2):
    sph_ver_1 = format_patch_version(version1)
    sph_ver_2 = format_patch_version(version2)
    if sph_ver_1 == sph_ver_2:
        return 0
    return 1 if sph_ver_1 > sph_ver_2 else -1


def format_patch_version(version):
    find_versions = re.findall(r"SPH(\d+)", version)
    sph_ver = find_versions[0] if find_versions else "0"
    return "SPH{}".format(sph_ver.zfill(5))