# By: Riasat Ullah
# This file contains variables specifically for Freshservice.

from requests.auth import HTTPBasicAuth
from constants import var_names
import requests


# url paths
freshservice_field_types_path_format = 'https://{0}/api/v2/ticket_form_fields'
freshservice_workspaces_path_format = 'https://{0}/api/v2/workspaces'


def get_freshservice_meta_data(domain, api_key):
    '''
    Get Freshservice ticket types from the client's Freshservice account.
    :param domain: Freshservice domain
    :param api_key: Freshservice api key
    :return: (tuple) -> status code, {ticket_type: [...], workspace: [...]}
    '''
    sts_code, sts_output = 200, {var_names.ticket_type: [], var_names.workspace: []}

    resp_wsp = requests.get(freshservice_workspaces_path_format.format(domain), auth=HTTPBasicAuth(api_key, 'x'))
    wsp_sts, wsp_out = resp_wsp.status_code, resp_wsp.json()
    if wsp_sts in (200, 201):
        sts_output[var_names.workspace] = sorted([[x['name'], x['id']] for x in wsp_out['workspaces']])

        # Freshservice only supports the "Incident" ticket type. That's why we have commented out this part for now.

        # resp_fields = requests.get(freshservice_field_types_path_format.format(domain),
        #                            auth=HTTPBasicAuth(api_key, 'x'))
        # fields_sts, fields_out = resp_fields.status_code, resp_fields.json()
        # if fields_sts in (200, 201):
        #     for field in fields_out['ticket_fields']:
        #         if field['name'] == 'ticket_type' and field['default_field']:
        #             sts_output[var_names.ticket_type] = sorted([[x['value'], x['value']] for x in field['choices']])
        #             break
        # else:
        #     sts_code = fields_sts
    else:
        sts_code = wsp_out

    return sts_code, sts_output
