# -*- coding:utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import json
import traceback

from utils.common.exception import HCCIException
from utils.business.project_util import ProjectApi
from plugins.DistributedStorage.Deploy.scripts.PreCheck.common.device_operate import PreCheckPublicOperate


class CustomizeCondition:
    def __init__(self, project_id, cmdb_info):
        self.project_id = project_id
        self.cmdb_info = cmdb_info
        self.project_api = ProjectApi()

    @classmethod
    def get_one_step_upgrade_condition(cls):
        upgrade_storage_hot_patch = 0
        if PreCheckPublicOperate.get_cfg_info().get("plugins_version", "patch_version"):
            upgrade_storage_hot_patch = 1
        return upgrade_storage_hot_patch

    def execute(self):
        try:
            custom_condition = {
                "IsTenantStorFB80": self._get_distributed_storage_condition(),
                "OneStepUpgrade": self.get_one_step_upgrade_condition()
            }
        except Exception as err:
            error_info = "get DistributedStorage custom condition error: {}, " \
                         "details:{}".format(err, traceback.format_exc())
            raise HCCIException(error_info) from err
        return json.dumps(custom_condition)

    def _get_distributed_storage_condition(self):
        project_info = self.project_api.get_project_info(self.project_id)
        region_id = project_info.get("region_id")
        current_region_cmdb_info = self.cmdb_info.get_region_infos(region_id)
        region_infos_az = current_region_cmdb_info.get("az")
        is_tenant_stor_fb = 0
        for item in region_infos_az:
            if item.get('virtualizeType') == 'kvm' and item.get('manager') is False \
                    and item.get('backendStorType') == "fusionstorage":
                is_tenant_stor_fb = 1
                break
        return is_tenant_stor_fb
