# -*- coding: utf-8 -*-
import traceback
import utils.common.log as logger
from utils.common.exception import FCDException
from utils.common.fic_base import TestCase
from utils.common.message import Message
from plugins.DistributedStorage.scripts.utils.common.DeployConstant \
    import DeployConstant
from utils.client.FSPAuthClient import FSPAuthClient
from utils.Driver.CloudDC.OpenStack.platform.ntp import NtpParamgetter
from plugins.DistributedStorage.scripts.logic.InstallOperate \
    import InstallOperate
from plugins.DistributedStorage.scripts.logic.DeployOperate import DeployOperate


class ConfigFinalItems(TestCase):
    def __init__(self, project_id, pod_id, fs_args, **kwargs):
        super(ConfigFinalItems, self).__init__(project_id, pod_id)
        self.operate = InstallOperate(self.project_id, self.pod_id, fs_args)
        self.opr = DeployOperate(float_ip=fs_args.get("float_ip"))
        self.vbs_list = fs_args.get('vbs_list')
        self.need_config_ntp_condition = fs_args.get(
            'need_config_ntp_condition')
        self.time_zone = fs_args.get('time_zone')
        self.update_pwd = fs_args.get('dm_update_pwd')

    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)

        # 获取时区
        if self.time_zone:
            logger.info("config time zone %s" % self.time_zone)
            # 配置FSM节点时区
            rsp_result, rsp_data = self.opr.put_time_zone(self.time_zone)
            if rsp_result.get("code") != 0:
                err_msg = "set timezone failed, " \
                          "Detail:[%s] %s" % (rsp_result, rsp_data)
                logger.error(err_msg)
                raise Exception(err_msg)
            else:
                logger.info("Set time zone success")

        # 获取内部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)

        # 配置FSM节点
        logger.info("Begin to config ntp")
        # 检查NTP服务器
        rsp_result, rsp_data = self.opr.valid_ntp_server(ntp_ip)
        if rsp_result.get("code") != 0:
            err_msg = "Check ntp server failed, " \
                      "Detail:[%s] %s" % (rsp_result, rsp_data)
            logger.error(err_msg)
            raise Exception(err_msg)
        else:
            logger.info("Check ntp server success")

        # 配置FSM节点NTP服务
        rsp_result, rsp_data = self.opr.put_ntp_server(ntp_ip)
        if rsp_result.get("code") != 0:
            err_msg = "set ntp server failed, " \
                      "Detail:[%s] %s" % (rsp_result, rsp_data)
            logger.error(err_msg)
            raise Exception(err_msg)
        else:
            logger.info("Set ntp server success")
        logger.info("Config ntp Success")

    def procedure(self):
        try:
            # 对扩容复用和扩容云服务场景不用配置ntp服务
            if self.need_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 FCDException as e:
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error(traceback.format_exc())
            raise e
        finally:
            self.opr.logout()
        return Message()
