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

from common import cliUtils
from common import resourceParse
from common.baseFactory import log


# 仅支持2200 V3 Nas的补丁版本号
PATCH_ONLY_4_NAS = ["V300R006C00SPH116",
                    "V300R006C10SPH107",
                    "V300R006C20SPH023",
                    "V300R006C20SPH118",
                    "V300R006C50SPH115",
                    "V300R006C60SPH003"]

NO_NAS_CAPACITY = "8.000GB"
NEED_CHECK_DEVTYPE = ["2200 V3", "2200 V3 Enhanced"]


def execute(data_dict):
    """
    范围中版本只适用于支持NAS特性的OceanStor 2200 V3存储设备（内存规格：16G/控制器）
    OceanStor 2200 V3 V300R006C00SPH116
    OceanStor 2200 V3 V300R006C10SPH107
    OceanStor 2200 V3 V300R006C20SPH023
    OceanStor 2200 V3 V300R006C20SPH118
    OceanStor 2200 V3 V300R006C50SPH115
    OceanStor 2200 V3 V300R006C60SPH003
    """
    patch_pkg_version = data_dict.get("pkgVersion")
    log.info(data_dict, "Current patch package version:{}".
             format(patch_pkg_version))
    if patch_pkg_version not in PATCH_ONLY_4_NAS:
        return True, "", ""

    device_type = str(data_dict.get('dev').getDeviceType())

    if device_type not in NEED_CHECK_DEVTYPE:
        return True, "", ""

    lang = data_dict['lang']
    resource = resourceParse.execute(lang)
    flag, capacity = get_cache_capacity(data_dict)
    if not flag:
        err_msg = resource.get("AdPatchForNasCheck.GetCacheCapacity.error")
        return False, err_msg, ""
    if capacity == NO_NAS_CAPACITY:
        err_msg = resource.get("AdPatchForNasCheck.notpass") % patch_pkg_version
        return False, err_msg, ""

    return True, "", ""


def get_cache_capacity(data_dict):
    """
    获取设备内存规格
    :param data_dict: 上下文
    :return: 内存信息
    """
    cli = data_dict.get("ssh")
    cmd = "show controller general |filterColumn include columnList" \
          "=Cache\\sCapacity"
    excute_ret = cliUtils.excuteCmdInCliMode(cli, cmd, True)
    cli_ret = excute_ret[1]
    cli_ret_lines_list = cli_ret.splitlines()
    cache_capacity_list = []

    for line in cli_ret_lines_list:
        fields = line.split(":")
        if len(fields) < 2:
            continue

        field_name = fields[0].strip()
        field_value = fields[1].strip()

        if field_name == "Cache Capacity":
            cache_capacity_list.append(field_value)

    if __check_capacity_valid(data_dict, cache_capacity_list):
        return True, cache_capacity_list[0]

    return False, ""


def __check_capacity_valid(data_dict, cache_capacity_list):
    if len(cache_capacity_list) == 0:
        log.info(data_dict, "cannot get cacheCapacity info.")
        return False
    if len(set(cache_capacity_list)) != 1:
        log.info(data_dict, "cache capacity is diffrent.")
        return False
    return True
