# -*- coding: utf-8 -*-
import time
import utils.common.log as logger
from utils.common.exception import FCDException as FCUException
from plugins.DistributedStorage.scripts.logic.UpgradeOperate import UpgradeOperate
from utils.common.fic_base import TestCase
import traceback


class PreUpgradeCheck(TestCase):
    def __init__(self, project_id, pod_id, fs_args, condition=None,
                 metadata=None, **kwargs):
        super(PreUpgradeCheck, self).__init__(project_id, pod_id)
        self.condition = condition
        self.metadata = metadata
        self.more_args = kwargs
        self.opr = UpgradeOperate(fs_args)
        self.user_name = fs_args.get("user_name", "admin")
        self.password = fs_args["dm_update_pwd"]

    def procedure(self):
        logger.info('Start upgrade task.')
        try:
            status_code, error_code, error_des = self.opr.try_login(
                self.user_name, self.password)
            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 FCUException(626313, err_msg)

            rsp_result, rsp_data = self.opr.get_product()
            if rsp_result.get("code") != 0:
                err_msg = "Failed to get product, Detail:[result:%s]%s" % (
                    rsp_result, rsp_data)
                logger.error(err_msg)
                raise FCUException(626313, err_msg)
            version = rsp_data.get("version")
            if version == "8.0.1.SPC600":
                logger.info('pre upgrade check.')
                self.pre_check_checker()
            else:
                logger.error("version is %s, skip!" % rsp_data)
        except FCUException as e:
            logger.error(traceback.format_exc())
            raise e
        except Exception as e:
            logger.error(traceback.format_exc())
            raise e
        finally:
            logger.info('procedure end.')

    def pre_check_checker(self):
        ret_result, ret_data = self.opr.pre_check()
        if ret_result["code"] != '0':
            err_msg = "pre upgrade check failed, Detail:[result:%s, data:%s]" \
                      % (ret_result, ret_data)
            logger.error(err_msg)
            raise FCUException(626313, err_msg)
        logger.info('get pre upgrade check status.')
        check_timeout = 3600
        while check_timeout > 0:
            ret_result, ret_data = self.opr.get_pre_check_status()
            if ret_result["code"] != '0':
                err_msg = "set upgrade to version mode failed, Detail:" \
                          "[result:%s, data:%s]" % (ret_result, ret_data)
                logger.error(err_msg)
                raise FCUException(626313, err_msg)
            if ret_data["status"] == "precheck_success":
                logger.info("pre check success")
                break
            elif ret_data["status"] == "precheck_failure":
                failed_component = ret_data.get("precheckignComponent")
                check_progress = ret_data["progress"]
                err_msg = "[%s] pre-check failed, progress [%s]" % (
                    failed_component, str(check_progress))
                logger.error("%s, Detail:[result:%s, data:%s]" % (
                    err_msg, ret_result, ret_data))
                raise FCUException(626313, err_msg)
            elif ret_data["status"] == "precheck":
                logger.info("pre check status result: %s, data: %s"
                            % (ret_result, ret_data))
            else:
                logger.error("pre check status failed. result: %s, data: %s"
                             % (ret_result, ret_data))
            time.sleep(10)
            check_timeout -= 10
        if check_timeout <= 0:
            failed_component = ret_data.get("precheckignComponent")
            check_progress = ret_data["progress"]
            err_msg = "[%s] pre-check timeout, progress [%s]" \
                      % (failed_component, str(check_progress))
            logger.error("%s, Detail:[result:%s, data:%s]"
                         % (err_msg, ret_result, ret_data))
            raise FCUException(626313, err_msg)
