# By: Riasat Ullah
# This file contains Prometheus integration related views.

from data_syncers import syncer_services, syncer_task_instances
from dbqueries import db_integrations
from exceptions.user_exceptions import InvalidRequest
from integrations import prometheus
from modules.router import Router
from objects.events import ResolveEvent
from objects.task_payload import TaskPayload
from rest_framework.decorators import api_view
from rest_framework.response import Response
from translators import label_translator as _lt
from utils import constants, errors, info, key_manager, logging, times, var_names
from utils.db_connection import CACHE_CLIENT, CONN_POOL
from validations import request_validator
import configuration


@api_view(['POST'])
def process_incoming_webhook(request, integration_key, conn=None, cache=None):
    '''
    Processes the incoming webhook from Prometheus.
    :param request: Http request
    :param integration_key: integration key passed in the url
    :param conn: db connection
    :param cache: cache client
    :return: Http response
    '''
    if request.method == 'POST':
        lang = request_validator.get_user_language(request)
        try:
            conn = CONN_POOL.get_db_conn() if conn is None else conn
            cache = CACHE_CLIENT if cache is None else cache

            unmasked_integ_key = key_manager.unmask_reference_key(integration_key)

            prm_receiver = request.data[prometheus.var_receiver]
            prm_status = prometheus.resolved_state\
                if prometheus.has_any_resolved_alert(request.data[prometheus.var_alerts])\
                else request.data[prometheus.var_status]
            prm_alert = request.data[prometheus.var_alerts][0]
            prm_alert_labels = prm_alert[prometheus.var_labels] if prometheus.var_labels in prm_alert else None
            prm_alert_annotations = prm_alert[prometheus.var_annotations]\
                if prometheus.var_annotations in prm_alert else None
            prm_alert_severity = prm_alert_labels[prometheus.var_severity]\
                if prm_alert_labels is not None and prometheus.var_severity in prm_alert_labels else None
            prm_link = prm_alert[prometheus.var_generator_url] if prometheus.var_generator_url in prm_alert else None
            prm_finger_print = prm_alert[prometheus.var_fingerprint]\
                if prometheus.var_fingerprint in prm_alert else None

            urgency = prometheus.severity_map[prm_alert_severity]\
                if prm_alert_severity in prometheus.severity_map else constants.critical_urgency

            # try to find the alert title
            if prometheus.var_summary in prm_alert_annotations:
                alert_title = prm_alert_annotations[prometheus.var_summary]
            elif prometheus.var_description in prm_alert_annotations:
                alert_title = prm_alert_annotations[prometheus.var_description]
            elif prometheus.var_alert_name in prm_alert_labels:
                alert_title = prm_alert_labels[prometheus.var_alert_name] + ' ' + prm_status
            else:
                alert_title = prometheus.general_alert_name + ' - ' + prm_status

            # try to find the alert body
            if prometheus.var_description in prm_alert_annotations:
                alert_body = prm_alert_annotations[prometheus.var_description] + '\n\n' + str(request.data)
            else:
                alert_body = str(request.data)

            current_time = times.get_current_timestamp()
            integ_id, serv_id, org_id = syncer_services.get_integration_key_details(
                conn, cache, current_time, unmasked_integ_key)

            integ_insts = db_integrations.get_integration_open_instances_trigger_info(
                conn, current_time, org_id, serv_id, integ_id)

            match_count = 0
            for inst_id, task_id, trig_info in integ_insts:
                if trig_info is not None:
                    source_payload = trig_info[var_names.source_payload]
                    source_alert = source_payload[prometheus.var_alerts][0]

                    # Update the status of the instance created if this is a recovery alert.
                    if source_payload[prometheus.var_receiver] == prm_receiver and (
                            (prometheus.var_fingerprint in source_alert and
                             source_alert[prometheus.var_fingerprint] == prm_finger_print) or
                            (prometheus.var_generator_url in source_alert and
                             source_alert[prometheus.var_generator_url] == prm_link)):
                        match_count += 1

                        # Group the alert if one already exists
                        if prm_status == prometheus.firing_state:
                            payload = TaskPayload(
                                current_time, org_id, current_time.date(), alert_title, configuration.standard_timezone,
                                current_time.time(), text_msg=alert_body, urgency_level=urgency,
                                trigger_method=constants.integrations_api, trigger_info=request.data,
                                integration_id=integ_id, integration_key=integration_key, service_id=serv_id,
                                instantiate=False, alert=False, related_task_id=task_id,
                                task_status=constants.grouped_state, vendor_incident_url=prm_link
                            )
                            Router(conn, cache, payload).start()
                        elif prm_status == prometheus.resolved_state:
                            event = ResolveEvent(inst_id, current_time, constants.integrations_api)
                            syncer_task_instances.resolve(conn, cache, event, org_id, is_sys_action=True)

            # Create a new task if this is a new alert.
            if match_count == 0 and prm_status == prometheus.firing_state:
                payload = TaskPayload(
                    current_time, org_id, current_time.date(), alert_title, configuration.standard_timezone,
                    current_time.time(), text_msg=alert_body, urgency_level=urgency,
                    trigger_method=constants.integrations_api, trigger_info=request.data, integration_id=integ_id,
                    integration_key=integration_key, service_id=serv_id, vendor_incident_url=prm_link
                )
                Router(conn, cache, payload).start()

            return Response(info.msg_internal_success)
        except InvalidRequest as e:
            logging.exception(str(e))
            return Response(_lt.get_label(errors.err_invalid_request, lang), status=400)
        except Exception as e:
            logging.exception(str(e))
            return Response(_lt.get_label(errors.err_system_error, lang), status=500)
        finally:
            CONN_POOL.put_db_conn(conn)
