#!/usr/bin/python
# -*- coding: UTF-8 -*-
import traceback
from collections import namedtuple
from utils.common.software_package_util import find_software_package
from utils.common.exception import HCCIException
import utils.common.log as logger
from utils.business.param_util import ParamUtil
from utils.common.fic_common import GetConfig


class ParamsGain(object):
    def __init__(self, project_id, pod_id, regionid_list):
        self.project_id = project_id
        self.pod_id = pod_id
        self.region_id = regionid_list[0]
        self.service_name = "DistributedStorage"

    def get_args(self, suit_id):
        params_dict = ParamUtil().get_service_cloud_param(
            self.project_id, self.service_name, self.region_id)
        fs_args = dict()
        node = namedtuple("node", ["ip", "user_name", "passwd", "root_pwd"])
        logger.info('suit_id is %s.' % str(suit_id))
        fs_args["float_ip"] = params_dict.get(
            "FSM_{}_float_ip".format(suit_id))
        logger.info("node is %s " % str(fs_args["float_ip"]))
        fs_args["port"] = "8088"
        fs_args["user_name"] = params_dict.get(
            "FSM_{}_rest_user".format(suit_id))
        fs_args["password"] = params_dict.get(
            "FSM_{}_rest_pwd".format(suit_id))
        fs_args["master_ip"] = params_dict.get(
            "FSM_{}_active_ip".format(suit_id))
        fs_args["master_username"] = params_dict.get(
            "FSM_{}_active_user".format(suit_id))
        fs_args["master_password"] = params_dict.get(
            "FSM_{}_active_pwd".format(suit_id))
        fs_args["master_root_pwd"] = params_dict.get(
            "FSM_{}_active_root_pwd".format(suit_id))
        fs_args["slaver_ip"] = params_dict.get(
            "FSM_{}_standby_ip".format(suit_id))
        fs_args["slaver_username"] = params_dict.get(
            "FSM_{}_standby_user".format(suit_id))
        fs_args["slaver_password"] = params_dict.get(
            "FSM_{}_standby_pwd".format(suit_id))
        fs_args["slaver_root_pwd"] = params_dict.get(
            "FSM_{}_standby_root_pwd".format(suit_id))
        fs_args["dmk_init_pwd"] = params_dict.get(
            "DMKInitPassword")
        fs_args["dmk_pwd"] = params_dict.get(
            "DMKUpdatePassword")
        fs_args["region_id"] = self.region_id
        fs_args["hot_patch_tag"] = self.get_hot_flag()
        fs_args["rollback_product_tag"] = self.get_rollback_product_flag()
        fs_args["quorum_server_pwd"] = params_dict.get("QuorumServerPwd")
        fs_args["quorum_server_ip"] = params_dict.get("QuorumServerIP")
        fs_args["master_node"] = node(fs_args.get("master_ip"), fs_args.get("master_username"),
                                      fs_args.get("master_password"), fs_args.get("master_root_pwd"))
        fs_args["slaver_node"] = node(fs_args.get("slaver_ip"), fs_args.get("slaver_username"),
                                      fs_args.get("slaver_password"), fs_args.get("slaver_root_pwd"))
        fs_args["suit_id"] = suit_id
        return fs_args

    @staticmethod
    def get_hot_flag():
        conf_obj = GetConfig(path='/plugins/DistributedStorage/utils/common/config.ini')
        hot_patch_tag = conf_obj.get_item('hot_patch_tag', 'hot_patch_tag')
        return hot_patch_tag == '1'

    @staticmethod
    def get_rollback_product_flag():
        conf_obj = GetConfig(path='/plugins/DistributedStorage/utils/common/config.ini')
        roll_back_product_tag = conf_obj.get_item('rollback_product_tag', 'rollback_product_tag')
        return roll_back_product_tag == '1'

    def get_storage_package(self):
        pkg_regular = r"^OceanStor-Pacific_8\.([0-9\._]|SPC|RC|HP)+\.tar\.gz$"
        return self.get_package(pkg_regular)

    def get_storage_hot_package(self):
        pkg_regular = r"^OceanStor-Pacific_8.[0-9.]+SPH[0-9]+.tar.gz$"
        return self.get_package(pkg_regular)

    def get_quorum_package(self):
        pkg_regular = r"^OceanStor-Pacific_8.[1-9].([0-9._]|SPH|SPC|RC|HP)+_QuorumServer.tar.gz$"
        return self.get_package(pkg_regular)

    def get_package(self, regular):
        try:
            pkg_dict, num = find_software_package(regular, self.project_id)
            if num > 1:
                logger.error("The package is not unique. %s" % str(pkg_dict))
                raise HCCIException(620020)
            if not pkg_dict:
                logger.error("The package NULL.")
                raise HCCIException(620019)
            pkg_name = list(pkg_dict.keys())[0]
            pkg_dir = list(pkg_dict.values())[0]
            return pkg_name, pkg_dir
        except Exception:
            logger.error(traceback.format_exc())
            error_msg = "get pkg %s failed" % regular
            logger.error(error_msg)
            raise HCCIException(620006, error_msg)
