# By: Riasat Ullah
# This file contains all constants and functions related to the CrowdStrike integration.

from utils import constants

# CrowdStrike main variables
var_data = 'data'
var_meta = 'meta'

# Sub-variables of the meta attribute
var_meta_event_reference_url = 'event_reference_url'
var_meta_trigger_name = 'trigger_name'

# Sub-variables of the data attribute
var_data_detections_action_taken = 'detections.action_taken'
var_data_detections_id = 'detections.id'
var_data_detections_severity = 'detections.severity'
var_data_detections_status = 'detections.status'
var_data_detections_url = 'detections.url'
var_data_devices_hostname = 'devices.hostname'
var_data_devices_tags = 'devices.tags'

# CrowdStrike status
status_closed = 'closed'
status_ignored = 'ignored'
status_new = 'new'
status_reopened = 'reopened'

# CrowdStrike trigger types
trigger_detections_new = 'detections.new'
trigger_detections_status_update = 'detections.status_update'

# CrowdStrike severity mapped to TaskCall urgency
severity_map = {
    'Critical': constants.critical_urgency,
    'High': constants.high_urgency,
    'Medium': constants.medium_urgency,
    'Low': constants.low_urgency,
    'Informational': constants.minor_urgency
}

# Internal detection type ID
new_detection_type_id = 1
reopened_detection_type_id = 2
existing_detection_type_id = 3


def get_internal_detection_type_id(meta_body, data_body):
    '''
    Get the internalized TaskCall issued detection type of the alert. This is only for internal use.
    :param meta_body: meta attribute from the payload
    :param data_body: data attribute from the payload
    :return: (int) 1 -> new; 2 -> reopened; 3 -> all else
    '''
    if meta_body[var_meta_trigger_name] == trigger_detections_new:
        return new_detection_type_id
    elif meta_body[var_meta_trigger_name] == trigger_detections_status_update\
            and data_body[var_data_detections_status] == status_reopened:
        return reopened_detection_type_id
    else:
        return existing_detection_type_id


def get_standardized_detection_id_from_event_url(meta_body):
    '''
    Gets the standardized detection ID from event url in the 'meta' attribute.
    :param meta_body: the meta attribute from the payload
    :return: (str) standardized detection ID
    '''
    event_ref_url = meta_body[var_meta_event_reference_url]
    return ':'.join(event_ref_url.split('?')[0].split('/')[-2:])


def get_standardized_detection_id_from_data_body(data_body):
    '''
    Gets the standardized detection ID from the 'data' attribute.
    :param data_body: the data attribute from the payload
    :return: (str) standardized detection ID
    '''
    return ':'.join(data_body[var_data_detections_id].split(':')[-2:])
