# -*- coding: utf-8 -*-
import utils.common.log as logger
from utils.client.service_om_client import ServiceOMClient as serviceOM_client
from utils.DBAdapter.DBConnector import BaseOps
from platforms.project.ProjectUtils import get_project_condition_boolean


class ServiceOMAlarm(object):
    def __init__(self, project_id, pod_id):
        self.project_id = project_id
        self.pod_id = pod_id
        self.db = BaseOps()
        if get_project_condition_boolean(self.project_id,
                                         'ExpansionAZ_KVM&MultiStorageInOneAZ&(TenantStorIPSAN|TenantStorFCSAN)'
                                         '|ExpansionServiceStorage&TenantStorFB80'):
            self.service_om_floatip = self.db.get_user_input_cloud_param_by_key(self.project_id, "service_om_ip")
            service_om_pwd = self.db.get_user_input_cloud_param_by_key(self.project_id, "serviceom_password")
        else:
            self.service_om_floatip = self.db.get_value_from_cloudparam(self.pod_id, "serviceOM", "OMFloatingIP")
            service_om_pwd = self.db.get_value_from_cloudparam(self.pod_id, "serviceOM", "serviceOM_webui_password")

        if not self.service_om_floatip:
            err_msg = "Failed to get service OM float IP"
            logger.info(err_msg)
            raise Exception(err_msg)
        if not service_om_pwd:
            err_msg = "Failed to get service OM pwd"
            logger.info(err_msg)
            raise Exception(err_msg)

        self.region = self.db.get_user_input_cloud_param_by_key(self.project_id, "openstack_region")
        if not self.region:
            err_msg = "Failed to get OpenStack region"
            logger.info(err_msg)
            raise Exception(err_msg)

        service_om_user = "admin"
        auth_provider = {"ip": self.service_om_floatip,
                         "port": "664",
                         "username": service_om_user,
                         "password": service_om_pwd,
                         "clientIP": self.service_om_floatip}
        self.operate = serviceOM_client(auth_provider)

    def mask_alarm(self):
        method = "POST"
        req_url = "solightuikitservice/rest/v1/command/frameworkpkg"
        body_data = {"ci": "AlarmShield",
                     "action": "Add",
                     "attrValues": {
                         "pod": self.region,
                         "shieldAlarmList": [{
                             "alarmid": "73203",
                             "compType": "OpenStack"}]
                         }
                     }
        logger.info("request mask body: %s" % body_data)
        cmd = {"body": body_data, "method": method, "uri": req_url}
        status, header, data = self.operate.exec_cmd(cmd)
        logger.info("mask alarm: status:%s, detail:%s" % (status, data))

    def query_alarm(self):
        method = "POST"
        req_url = "solightuikitservice/rest/v1/command/frameworkpkg"
        body_data = {"ci": "AlarmList",
                     "action": "Query",
                     "attrValues": {
                         "omPage": {
                             "limit": 100,
                             "start": 0},
                         "tag": "region.openstackom.cascading-{}".format(self.region),
                         "inquiryCond": {"alarmtype": 1}
                         }
                     }
        logger.info("request query body: %s" % body_data)
        cmd = {"body": body_data, "method": method, "uri": req_url}
        status, header, data = self.operate.exec_cmd(cmd)
        logger.info("mask alarm: status:%s, detail:%s" % (status, data))
        return data

    @staticmethod
    def filter_target_alarm(alarm_data, alarm_id):
        alarm_list = list()
        for alarm in alarm_data:
            if alarm.get('alarmId') == alarm_id:
                curr_alarm = dict()
                curr_alarm['alarmID'] = alarm.get('alarmId')
                curr_alarm['sn'] = alarm.get('sn')
                curr_alarm['resourceID'] = alarm.get('resourceID')
                curr_alarm['compId'] = alarm.get('compId')
                alarm_list.append(curr_alarm)
        logger.info("alarm list: %s" % alarm_list)
        return alarm_list

    def clear_alarm(self, alarm_list):
        method = "POST"
        req_url = "solightuikitservice/rest/v1/command/frameworkpkg"
        body_data = {"ci": "AlarmList",
                     "action": "Clear",
                     "attrValues": {
                         "pod": "cascading-{}".format(self.region),
                         "casadingType": "cascading",
                         "clearAlarm": alarm_list
                         }
                     }
        logger.info("request clear body: %s" % body_data)
        cmd = {"body": body_data, "method": method, "uri": req_url}
        status, header, data = self.operate.exec_cmd(cmd)
        logger.info("mask alarm: status:%s, detail:%s" % (status, data))

    def clear_reported_alarm(self):
        target_alarm_id = '73203'
        all_alarm_data = self.query_alarm()
        alarm_list = self.filter_target_alarm(all_alarm_data.get('data').get('data'), target_alarm_id)
        if alarm_list:
            self.clear_alarm(alarm_list)

    def delete_mask_alarm(self):
        method = "POST"
        req_url = "solightuikitservice/rest/v1/command/frameworkpkg"
        body_data = {"ci": "AlarmShield",
                     "action": "Delete",
                     "attrValues": {
                         "pod": "evs.hcs8type3",
                         "shieldAlarmList": [{
                             "alarmid": "73203",
                             "compType": "OpenStack",
                             "objectId": "ALL",
                             "objectType": "ALL"}]
                         }
                     }
        logger.info("request delete body: %s" % body_data)
        cmd = {"body": body_data, "method": method, "uri": req_url}
        status, header, data = self.operate.exec_cmd(cmd)
        logger.info("mask alarm: status:%s, detail:%s" % (status, data))
