# coding=utf-8
from utils.common.exception import HCCIException
from utils.common.message import Message
from utils.common.fic_base import StepBaseInterface
from utils.DBAdapter.DBConnector import BaseOps
from utils.business.project_condition_utils import get_project_condition_boolean
import utils.common.log as logger
from utils.business.vm_util import can_vm_pinged_to


class CheckIPOccupy(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(CheckIPOccupy, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()

    def pre_check(self, project_id, pod_id):
        """
        插件内部接口：执行安装前的资源预检查，该接口由execute接口调用，工具框架不会直接调用此接口。
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def execute(self, project_id, pod_id):
        try:
            self.procedure(project_id)
            return Message(200)
        except HCCIException as e1:
            return Message(500, e1)
        except Exception as e2:
            return Message(500, HCCIException('626273', str(e2)))

    def rollback(self, project_id, pod_id):
        """
        标准调用接口：执行回滚
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def retry(self, project_id, pod_id):
        """
        标准调用接口：重试
        :return: Message类对象
        """
        return self.execute(project_id, pod_id)

    def check(self, project_id, pod_id):
        """
        标准调用接口：重试
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message(200)

    def procedure(self, project_id):
        params = dict()
        if get_project_condition_boolean(project_id, 'TenantStorFB80&(ExpansionAZ_KVM|ExpansionPOD_KVM|ExpansionAZ_BMS|ExpansionPOD_BMS)'):
            expansion_new_fsm_float_ip = self.db.get_user_input_cloud_param_by_key(project_id, "expansion_new_fsm_float_ip")
            params['expansion_new_fsm_float_ip'] = expansion_new_fsm_float_ip
        elif get_project_condition_boolean(project_id, 'TenantStorFB80&ExpansionServiceStorage'):
            expansion_fusionstorage_float_ip = self.db.get_user_input_cloud_param_by_key(project_id, "expansion_fusionstorage_float_ip")
            params['expansion_fusionstorage_float_ip'] = expansion_fusionstorage_float_ip

        ping_list = list()
        for key, value in params.items():
            logger.info("Start to ping %s[%s]" % (key, value))
            if can_vm_pinged_to(value):
                ping_list.append("{}:{}".format(key, value))

        if len(ping_list) > 0:
            logger.info("Succeed to ping ip address:%s" % ping_list)
            raise HCCIException(626308, ping_list)

