# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import traceback
import utils.common.log as logger
from utils.common.fic_base import TestCase
from utils.common.message import Message
from utils.common.exception import FCDException
from platforms.project.ProjectUtils import get_project_condition_boolean
from plugins.DistributedStorage.scripts.logic.DeployOperate import DeployOperate
from plugins.DistributedStorage.scripts.utils.common.DeployConstant import DeployConstant


class CreateClient(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(CreateClient, self).__init__(project_id, pod_id)
        self.fs_args = fs_args
        self.bmc_info_lists = self.db.get_install_os_list_info(self.pod_id)
        self.fsa_list = self.fs_args.get('fsa_list')
        self.vbs_list = self.fs_args.get('vbs_list')
        self.osd_list = self.fs_args.get('osd_list')
        self.opr = DeployOperate(self.fs_args)
        self.more_args = kwargs
        self.update_pwd = self.fs_args['dm_update_pwd']
        self.iscsi_condition = get_project_condition_boolean(self.project_id, 'TenantStorFB_iSCSI')

    def procedure(self):
        try:
            self.main()
        except FCDException as e:
            logger.error(traceback.format_exc())
            return Message(500, e)
        except Exception as e:
            logger.error(traceback.format_exc())
            return Message(500, FCDException(626001, str(e)))
        return Message()

    def main(self):
        logger.info("Start to create client.")
        self.opr.login(DeployConstant.DM_LOGIN_USER, self.update_pwd)
        logger.info('Check cluster...')
        res_cluster = self.opr.query_manage_cluster()
        cluster = res_cluster.get_query_data()
        if not cluster.get('clusterName'):
            logger.error('Check cluster fail...')
            raise Exception("Check cluster fail...")
        else:
            logger.error('Check cluster successfully...')
        logger.info('Check pool...')
        res_pool = self.opr.query_storage_pool()
        pool = res_pool.get_query_data()
        if len(pool.get('storagePools')) == 0:
            logger.error('Check pool fail...')
            raise Exception("Check pool fail...")
        else:
            logger.info('Check pool successfully...')
        logger.info("Check whether VBS is installed.")
        vbs_ip_list = []
        if self.vbs_list:
            vbs_ip_list = [vbs.get('om_ip') for vbs in self.vbs_list]
        elif self.iscsi_condition:
            osd_ip_list = [osd.get('om_ip') for osd in self.osd_list]
            vbs_ip_list.extend(osd_ip_list)
        else:
            err_msg = "vbs node is none"
            logger.error(err_msg)
            raise Exception(err_msg)
        logger.info("Check whether VBS is installed.")
        self.create_client(vbs_ip_list)
        # ISCSI网络配置单独提出一个工步，并不再创建客户端处进行配置
        logger.info('Create VBS client success')
        self.opr.login_out(DeployConstant.DM_LOGIN_USER, self.update_pwd)

    def get_vbs_ip_list(self, vbs_ip_list):
        rsp_obj = self.opr.query_cluster_servers()
        rsp_code, rsp_result, rsp_data = rsp_obj.get_rsp_data()
        error_code = rsp_result.get("code")
        if rsp_code != 0 or error_code != 0:
            error_des = rsp_result.get('description')
            error_sgt = rsp_result.get('suggestion')
            err_msg = "Failed to query the node to install vbs, Detail:[%s]%s.Suggestion:%s" % (
                error_code, error_des, error_sgt)
            logger.error(err_msg)
            raise Exception(err_msg)
        for server in rsp_data:
            ip = server.get('management_ip')
            if ip in vbs_ip_list and "vbs" in server.get('usage'):
                vbs_ip_list.remove(server.get('management_ip'))
                logger.info("VBS has been installed on node[%s]." % ip)

    def create_client(self, vbs_ip_list):
        self.get_vbs_ip_list(vbs_ip_list)
        if vbs_ip_list:
            logger.info('create VBS client.')
            res_client = self.opr.create_client(vbs_ip_list)
            status_code, result, _, _ = res_client.get_create_client_code()
            if status_code != 200 or result != 0:
                self.get_vbs_ip_list(vbs_ip_list)
                err_msg = "Failed to Create VBS client, Detail:{}".format(res_client.get_query_data())
                logger.error(err_msg)
                raise Exception(err_msg)
