# -*- coding:utf-8 -*-
from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
import utils.common.log as logger
from utils.business.dmk_util import DmkApi
from plugins.eBackup.common.eBackupUpgrade import EbackupUpgrader
from plugins.eBackup.common.util import precheck_ebackup
from plugins.eBackup.common.util import get_dmk_precheck_result
from plugins.eBackup.common.util import check_access_status
from plugins.eBackup.common.util import check_versions_compatibility
from utils.common.exception import FCUException
from plugins.eBackup.common.util import Utils
from plugins.eBackup.common.util import g_check_item
from platforms.upgradecheck.check_result import CheckResult


class WorkflowPrecheck(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list=None):
        super(WorkflowPrecheck, self).__init__(project_id, pod_id,
                                               regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.__dmk_util = DmkApi()
        self.param_dict = Utils.init_system_params(project_id,
                                                   regionid_list[0])

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            check_results = []
            server_ips = self.param_dict['eBackup_Workflow_nodes']
            server_ips = server_ips.replace(" ", "").replace("|", ";").\
                split(";")
            # 1.precheck by precheck_ebackup.sh
            logger.info("Begin to precheck nodes(%s) by HCU firstly." %
                        str(server_ips))

            is_true, error_info = check_versions_compatibility(
                server_ips,
                self.param_dict['eBackup_hcp_pwd'],
                self.param_dict['eBackup_root_pwd'])
            if not is_true:
                logger.error("version is not same.")
                raise FCUException(650044, error_info)

            is_true = precheck_ebackup(check_results, server_ips,
                                       self.param_dict['eBackup_hcp_pwd'],
                                       self.param_dict['eBackup_root_pwd'],
                                       self.param_dict['update_scene'],
                                       self.param_dict['dmk_floatIp'],
                                       self.param_dict['eBackup_Version'])
            if not is_true:
                logger.error("Precheck by HCU failed.")
                return Message(200, check_results=check_results)

            # 2.check acess status
            web_ip = Utils.find_float_ip(server_ips,
                                         self.param_dict['eBackup_hcp_pwd'],
                                         self.param_dict['eBackup_root_pwd'])
            is_true = check_access_status(check_results, web_ip,
                                          self.param_dict['eBackup_admin_pwd'],
                                          2)
            if not is_true:
                logger.error("Precheck assess status by FCU failed.")
                return Message(200, check_results=check_results)
            key = 'access_status'
            check_result = CheckResult(
                itemname_ch=g_check_item[key]['name_cn'],
                itemname_en=g_check_item[key]['name_en'],
                status="success")
            check_results.append(check_result)
            # 3.just for workflow at the time,it will be removed in
            # next version.
            # 3.precheck by DMK
            logger.info("Begin to precheck nodes(%s) by DMK secondly." %
                        str(server_ips))
            ebackup_upgrade = EbackupUpgrader(server_ips, self.param_dict,
                                              "workflow")
            is_true = ebackup_upgrade.precheck()

            if not is_true:
                logger.error("Precheck by DMK failed.")
                raise FCUException(650036)

            logger.info("Begin to get DMK precheck result.")
            is_true = get_dmk_precheck_result(
                check_results, server_ips,
                self.param_dict['eBackup_hcp_pwd'],
                self.param_dict['eBackup_root_pwd'],
                self.param_dict['eBackup_Version'])
            if not is_true:
                logger.error("Prechecking is unpassed by DMK.")

            logger.info("Precheck nodes(%s) completed." % server_ips)
            return Message(200, check_results=check_results)
        except FCUException as e:
            logger.error("Precheck failed: " + str(e))
            return Message(500, e)
        except Exception as e:
            logger.error("Failed to precheck Workflow ,the reason is %s" % e)
            return Message(
                500,
                error_msg_cn="升级前检查出现异常，请查看日志并重试，"
                             "异常信息:%s" % str(e),
                error_msg_en="Exception occurs  while prechecking,please "
                             "check the log and try again, error info:%s." %
                             str(e))

    def rollback(self, project_id, pod_id, regionid_list=None):
        return Message(200)

    def retry(self, project_id, pod_id, regionid_list=None):
        return self.execute(project_id, pod_id, regionid_list)
