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

import utils.common.log as logger
from utils.common.message import Message
from utils.common.exception import HCCIException
from utils.DBAdapter.DBConnector import BaseOps
from utils.common.fic_base import StepBaseInterface
from plugins.DistributedStorage.utils.iterm.parameter_gain import ParamsGain
from plugins.DistributedStorage.Expansion.scripts.CloudService.implement.tc_expand_pool import ExpandPool
from plugins.DistributedStorage.utils.common.deploy_constant import ComponentName


class ExpandServicePoolIntf(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()
        self.params = ParamsGain(project_id, pod_id, self.db)
        self.fs_args = self.params.get_business_separate_expand_fusionstorage_args_while_new_pool_or_new_node()
        osd_nodes_info = self.db.get_install_os_list_info(pod_id=self.pod_id)
        self.pool_node_map = collections.defaultdict(list)
        for node in osd_nodes_info:
            node['om_ip'] = node.pop('manageIp')
            self.pool_node_map[node.get("storage_pool_name_and_slot")].append(node)
        self.finish_exp_pool_key = "PoolFinishExpansion"

    def pre_check(self, project_id, pod_id):
        """
        插件内部接口：创建存储池，该接口由execute接口调用，工具框架不会直接调用此接口。
        :param project_id:
        :param pod_id:
        :return:
        """
        return Message()

    def execute(self, project_id, pod_id):
        try:
            self.main()
        except HCCIException as e:
            logger.error(traceback.format_exc())
            return Message(500, e)
        except Exception as e:
            logger.error(traceback.format_exc())
            return Message(500, HCCIException(626003, str(e)))
        return Message(200)

    def main(self):
        finish_exp_pool = self.db.get_value_from_cloudparam(
            self.project_id, ComponentName.DEPLOY, self.finish_exp_pool_key)
        logger.info("Disk pools that have been expanded:{}".format(finish_exp_pool.split(",")[1:]))

        for pool, node_list in self.pool_node_map.items():
            if finish_exp_pool.__contains__(pool):
                continue

            logger.info("Start expanding the disk pool:{}.".format(pool))
            self.fs_args['ex_osd_list'] = node_list
            try:
                ExpandPool(self.project_id, self.pod_id, self.fs_args).procedure()
            except Exception as err:
                _finish_list = finish_exp_pool.split(",")[1:]
                err_msg = f"Disk pools that are successfully expanded:{_finish_list}. " \
                          f"Failed to expand the disk pool:{pool}, details:{err}"
                logger.error(err_msg)
                raise HCCIException(626003, err_msg) from err

            finish_exp_pool = ",".join([finish_exp_pool, pool])
            self.db.update_cloud_param(
                ComponentName.DEPLOY,
                self.finish_exp_pool_key,
                self.project_id,
                self.pod_id,
                {"param_value": finish_exp_pool})

    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()
