# -*- 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.message import Message
from utils.common.fic_base import TestCase
from utils.common.exception import HCCIException
from plugins.DistributedStorage.logic.deploy_operate import DeployOperate
from plugins.DistributedStorage.utils.common.deploy_constant import DeployConstant


class ConfigISCSI(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(ConfigISCSI, self).__init__(project_id, pod_id)
        self.osd_list = fs_args.get('osd_list')
        self.update_pwd = fs_args['dm_update_pwd']
        self.opr = DeployOperate({'float_ip': fs_args.get('float_ip')})
        self.more_args = kwargs

    def procedure(self):
        logger.info("ISCSI NETWORK CONFIG START")
        try:
            self.login_deploy_manager()
        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)))
        try:
            self.config_iscsi_network()
        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)))
        else:
            logger.info("ISCSI NETWORK CONFIG END")
        finally:
            self.opr.logout()
        return Message()

    def login_deploy_manager(self):
        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)

    def config_iscsi_network(self):
        iscsi_configed_count = 0
        for fsa in self.osd_list:
            fsa_manage_ip = fsa.get('om_ip')
            iscsi_ip = fsa.get("iscsi_business_plane_ip")
            if not iscsi_ip:
                err_msg = "Failed to get iscsi ip,fsa ip is %s" % fsa_manage_ip
                logger.error(err_msg)
                raise Exception(err_msg)
            result = self.opr.config_iscsi_switch(fsa_manage_ip)
            succ_ip = result.get_iscsi_result()
            if not succ_ip:
                err_msg = "Failed to config iscsi switch, fsa ip=%s, result=%s" % (fsa_manage_ip, result.res.json())
                logger.error(err_msg)
                raise Exception(err_msg)
            result = self.opr.add_iscsi_portal(fsa_manage_ip, iscsi_ip)
            succ_ip = result.get_iscsi_result()
            if not succ_ip:
                error_code = result.res.json().get('detail')[0].get('errorCode')
                if error_code == 33760258:
                    iscsi_configed_count += 1
                    logger.info("The specified iSCSI IP address already exists on node[%s]." % fsa_manage_ip)
                    continue
                err_msg = "Failed to add iscsi portal, fsa ip=%s, iscsi ip=%s " \
                          "result=%s" % (fsa_manage_ip, iscsi_ip, result.res.json())
                logger.error(err_msg)
                raise Exception(err_msg)
            iscsi_configed_count += 1
        if 0 == iscsi_configed_count:
            err_msg = "Failed to add iscsi portal for fsa node, count = 0"
            logger.error(err_msg)
            raise Exception(err_msg)
        logger.info('Config iscsi service success, fsa count=%d' % iscsi_configed_count)
