# By: Riasat Ullah
# WARNING
# This file contains the functions necessary to trigger alerts internally to handle errors before they impact clients.
# These functions should only be used for TaskCall's internal communication.

from utils import file_storage, logging, mail, s3
from requests.auth import HTTPBasicAuth
import json
import requests


def dispatch_alerts(title, message):
    '''
    Dispatch alert notifications internally to handle errors.
    :param title: (str) title of the alert to be sent
    :param message: (str) main content of the alert
    '''
    alr_dt = s3.read_json(file_storage.S3_BUCKET_TASKCALL_PROD_DATA, file_storage.S3_KEY_INTERNAL_ALERTING_DETAILS)

    # send emails (to direct email addresses and to create incidents)
    try:
        email_credentials = mail.AmazonSesCredentials()
        mail.AmazonSesDispatcher(title, message, alr_dt['email'], email_credentials).start()
    except Exception as e:
        logging.info('INTERNAL ALERTING: Email & TaskCall Incident - Failed')
        logging.exception(str(e))

    # create Freshdesk ticket
    try:
        response = requests.post(
            'https://{0}/api/v2/tickets'.format(alr_dt['freshdesk']['domain']),
            auth=HTTPBasicAuth(alr_dt['freshdesk']['api_key'], 'x'),
            headers={'Content-Type': 'application/json'},
            data=json.dumps({
                'subject': title,
                'description': message,
                'type': 'Incident',
                'status': 2,
                'priority': 4,
                'unique_external_id': 'TaskCall'
            })
        )
        if response.status_code in [200, 201]:
            logging.info('INTERNAL ALERTING: Freshdesk ticket created - ' + str(response.json()['id']))
        else:
            logging.info('INTERNAL ALERTING: Freshdesk - Failed')
    except Exception as e:
        logging.info('INTERNAL ALERTING: Freshdesk - Failed')
        logging.exception(str(e))
