# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import utils.constant.constant as constant
from utils.DBAdapter.DBConnector import BaseOps
from utils.constant.FCDConstant import BMC_ROLE_INFO, get_compute_dpdk_hosts


class HostData(object):
    def __init__(self, project_id, pod_id):
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()

    @staticmethod
    def get_nodes_by_role_list(db, pod_id, bmc_role_white_list):
        node_list = list()
        nodes_info = db.get_bmc_info_by_pod_id(pod_id)
        for node in nodes_info:
            node_bmc_role = node["bmc_role"].replace(" ", "")
            bmc_role_list = node_bmc_role.split(',')
            for item in bmc_role_white_list:
                if item in bmc_role_list:
                    node_list.append(node)
                    break
        return node_list

    @staticmethod
    def get_vbs_ip_list(db, pod_id, is_business=False):
        nodes_info = db.get_ref_component_host_list(pod_id, constant.REFCOMPONENTCONSTANT.VBS)
        return HostData.__filter_storage_type_nodes(nodes_info, is_business)

    @staticmethod
    def get_data_intersection_by_bmc_ip(source_data, target_data):
        node_list = list()
        for src_data in source_data:
            for tgt_data in target_data:
                if src_data.get('bmc_ip') == tgt_data.get('bmc_ip'):
                    node_list.append(src_data)
                    break
        return node_list

    @staticmethod
    def get_business_node_list(node_list, nodes_info):
        for node in nodes_info:
            node_bmc_role = node.bmc_role.replace(" ", "")
            bmc_role_list = node_bmc_role.split(',')
            for item in BMC_ROLE_INFO.COMPUTE_ROLE_WHITE_LIST:
                if item in bmc_role_list:
                    node_info = {"bmc_ip": node.bmc_ip}
                    node_list.append(node_info)
                    break

    @staticmethod
    def __filter_storage_type_nodes(nodes_info, is_business=False):
        node_list = list()
        control_nodes = [constant.BMCROLE.FIRST_NODE, constant.BMCROLE.CONTROLLER_NODE,
                         constant.BMCROLE.CLOUD_SERVICE_NODE]
        if is_business:
            HostData.get_business_node_list(node_list, nodes_info)
        else:
            for unit in nodes_info:
                if unit.bmc_role in control_nodes:
                    node_list.append(unit)
        return node_list

    def get_separate_compute_node_list(self):
        x86_arm_compute_role_list = get_compute_dpdk_hosts()
        # 筛选适合的计算节点
        tsfb_compute_bmc_ip_list = self.get_nodes_by_role_list(self.db, self.pod_id, x86_arm_compute_role_list)

        all_vbs_bmc_list = self.get_vbs_ip_list(self.db, self.pod_id, is_business=True)
        vbs_bmc_list = self.get_data_intersection_by_bmc_ip(all_vbs_bmc_list, tsfb_compute_bmc_ip_list)
        return vbs_bmc_list
