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

from utils import constants, var_names
import json
import requests

# Rundeck alert triggers
trig_failure = 'failure'
trig_start = 'start'
trig_success = 'success'

# Rundeck alert statuses
sts_failed = 'failed'
sts_running = 'running'
sts_succeeded = 'succeeded'


def send_rundeck_instructions(integ_info):
    '''
    Sends instructions to Rundeck to start a job or run diagnostics.
    :param integ_info: additional info of this integration
    :return: (str) -> item ID (Monday returns an int, but we will convert it to a str as per our database requirements)
    '''
    url_path = integ_info[var_names.vendor_endpoint]
    auth_string = integ_info[var_names.secret_token]
    if var_names.payload in integ_info[var_names.additional_info] and\
            integ_info[var_names.additional_info][var_names.payload] is not None:
        data_to_send = json.loads(integ_info[var_names.additional_info][var_names.payload])
    else:
        data_to_send = dict()

    header_params = {
        'Accept': constants.content_type_json,
        'Content-Type': constants.content_type_json,
        'Authorization': auth_string
    }
    response = requests.post(url=url_path, headers=header_params, json=data_to_send)
    exec_id, status, addn_info = None, response.status_code, response.json()
    if status == 200:
        exec_id = addn_info['executionId']

        # We do this because the instance_custom_actions table expects the vendor ID to be a string.
        exec_id = str(exec_id)

    return exec_id, status, addn_info
