# -*- 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 utils.business.project_condition_utils import get_project_condition_boolean
from plugins.DistributedStorage.logic.InstallOperate import InstallOperate
from utils.client.FSPAuthClient import FSPAuthClient
from utils.Driver.CloudDC.OpenStack.platform.ntp import NtpParamgetter
from plugins.DistributedStorage.logic.DeployOperate import DeployOperate
from plugins.DistributedStorage.utils.common.DeployConstant import DeployConstant


class ConfigFinalItems(TestCase):
    def __init__(self, project_id, pod_id, fs_args, condition=None, metadata=None, **kwargs):
        super(ConfigFinalItems, self).__init__(project_id, pod_id)
        self.operate = InstallOperate(self.project_id, self.pod_id, fs_args)
        self.opr = DeployOperate(fs_args)
        self.condition = condition
        self.metadata = metadata
        self.more_args = kwargs
        self.update_pwd = fs_args['dm_update_pwd']
        self.vbs_list = fs_args.get('vbs_list')
        self.config_ntp_condition = get_project_condition_boolean(
            self.project_id,
            '!((TenantStorFBReuse80&(ExpansionAZ_KVM|ExpansionAZ_BMS))'
            '|ExpansionPOD_CloudService|ExpansionMgmtRes_ServiceNode|ExpansionScale_CloudServiceNode)')

    def config_ntp_service(self):
        logger.info("Start to login to fsm.")
        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)

        # 获取时区
        self.time_zone = self.db.get_user_input_cloud_param_by_key(self.project_id, "time_zone")
        if not self.time_zone:
            msg = "The timezone is empty, please check the parameters time_zone in lld"
            logger.error(msg)
        else:
            logger.info("config time zone %s" % self.time_zone)
            # 配置FSM节点时区
            rsp_obj = self.opr.set_time_zone(self.time_zone)
            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 set time zone, Detail:[%s]%s.Suggestion:%s" % (error_code, error_des, error_sgt)
                logger.error(err_msg)
                raise Exception(err_msg)

        # 获取内部NTP服务器
        cps_rest_client = FSPAuthClient.get_cps_rest_client(self.db, self.project_id, self.pod_id)
        ntp_ip = NtpParamgetter(cps_rest_client).get_extend_ip()
        if not ntp_ip:
            msg = "The ntp server is empty,Please manually configure the NTP service from the Fusionstorage page "
            logger.info(msg)
            raise Exception(msg)

        logger.info("Begin to config ntp")
        # 配置FSM节点
        # 检查NTP服务器
        rsp_obj = self.opr.check_ntp_server(ntp_ip)
        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 check ntp server, Detail:[%s]%s.Suggestion:%s" % (error_code, error_des, error_sgt)
            logger.error(err_msg)
            raise Exception(err_msg)

        # 配置FSM节点NTP服务
        rsp_obj = self.opr.set_ntp_server(ntp_ip)
        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 check ntp server, Detail:[%s]%s.Suggestion:%s" % (error_code, error_des, error_sgt)
            logger.error(err_msg)
            raise Exception(err_msg)
        logger.info("Config ntp Success")

    def procedure(self):
        try:
            # 对扩容复用和扩容云服务场景不用配置ntp服务
            if self.config_ntp_condition:
                logger.info("Config ntp service")
                self.config_ntp_service()

            logger.info("Turn of ntp service")
            for vbs in self.vbs_list:
                logger.info("Start to turn of root access of separate deployment node[%s]" % vbs.get('om_ip'))
                self.operate.disable_ntp_service(vbs.get('om_ip'), vbs.get('user'), vbs.get('passwd'),
                                                 vbs.get('root_pwd'))

        except HCCIException as e:
            logger.error(traceback.format_exc())
            return Message(500, e)
        except Exception as e:
            return Message(500, HCCIException(626088, str(e)))
        return Message()
