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

from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
from utils.common.exception import HCCIException
from utils.DBAdapter.DBConnector import BaseOps
import utils.common.log as logger
from plugins.DistributedStorage.Deploy.scripts.PreCheck.implement.job_disk_check import DiskCheck


class CheckCacheIntf(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()

    def pre_check(self, project_id, pod_id):
        """
        插件内部接口：
        :param project_id:
        :param pod_id:
        :return:
        """
        return Message()

    def execute(self, project_id, pod_id):
        """
        标准调用接口：
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        try:
            self.main(pod_id, project_id)
        except HCCIException as e1:
            return Message(500, e1)
        except Exception as e2:
            return Message(500, e2)
        return Message(200)

    def main(self, pod_id, project_id):
        err_info = []
        all_bmc_data = self.db.get_install_os_list_info(self.pod_id)
        pool_name_and_node_map = collections.defaultdict(list)
        for node in all_bmc_data:
            pool_name_and_node_map[node.get("storage_pool_name_and_slot")].append(node)

        for pool_name, bmc_data in pool_name_and_node_map.items():
            disk_check = DiskCheck(project_id, pod_id)
            error_dic, first_bmc_node = disk_check.check_storage_node_cache_disk(bmc_data)
            if not error_dic:
                continue

            error_nodes = disk_check.check_result_parsing(error_dic, first_bmc_node, pool_name)
            if error_nodes:
                logger.error(error_nodes)
                err_info.extend(error_nodes)

        if err_info:
            logger.error(err_info)
            raise Exception(err_info)

    def rollback(self, project_id, pod_id):
        """
        标准调用接口：执行回滚
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message()

    def retry(self, project_id, pod_id):
        """
        标准调用接口：重试
        :return: Message类对象
        """
        return self.execute(project_id, pod_id)

    def check(self, project_id, pod_id):
        """
        标准调用接口：重试
        :param project_id:
        :param pod_id:
        :return:
        """
        return Message()
