# By: Riasat Ullah
# This file contains all constants and functions for the custom action integration.

from utils import constants, logging, var_names
import requests


def send_instructions_to_custom_endpoint(integ_info, payload=None):
    '''
    Sends instructions to a custom endpoint.
    :param integ_info: additional info of this integration
    :param payload: (dict) the payload to send
    :return: request response status code
    '''
    url_path = integ_info[var_names.vendor_endpoint]
    header_params = integ_info[var_names.conditions_map]
    data_to_send = dict() if payload is None else payload

    if header_params is None:
        header_params = {
            'Accept': constants.content_type_json,
            'Content-Type': constants.content_type_json
        }

    response = requests.post(url=url_path, headers=header_params, json=data_to_send)
    exe_status = response.status_code
    try:
        exe_output = response.json()
    except Exception:
        logging.error('Failing to read custom action response: ' + str(response))
        exe_output = dict()

    if exe_status not in (200, 201):
        logging.error('Custom endpoint execution failed. Status code ' + str(exe_status))
        logging.error(exe_output)
    return exe_status, exe_output
