# -*- coding: utf-8 -*-
import traceback
from utils.common.fic_base import TestCase
import utils.common.log as logger
from utils.common.message import Message
from utils.common.exception import HCCIException
from plugins.DistributedStorage.logic.DeployOperate import DeployOperate
from plugins.DistributedStorage.utils.common.DeployConstant import DeployConstant
from utils.business.project_condition_utils import get_project_condition_boolean


class CreateClient(TestCase):
    def __init__(self, project_id, pod_id, fs_args, condition=None, metadata=None, **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.condition = condition
        self.metadata = metadata
        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:
            logger.info("Start to create client.")
            status_code, error_code, error_des = self.opr.login(DeployConstant.DM_LOGIN_USER, self.update_pwd)
            if status_code != 200 or error_code != 0:
                err_msg = "Failed to login deploy manager, Detail:[status:%s,code:%s]%s" % (status_code, error_code,
                                                                                            error_des)
                logger.error(err_msg)
                raise Exception(err_msg)

            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)
        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(626001, str(e)))
        return Message()

    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, error_code, error_des = 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:[status:%s,result:%s,error:%s, ip:%s]%s" \
                          % (status_code, result, error_code, vbs_ip_list, error_des)
                logger.error(err_msg)
                raise Exception(err_msg)
