# By: Riasat Ullah
# This module works with Slack integration data in the database.

from utils import integration_type_names
import datetime
import psycopg2


def get_slack_integration_details(conn, timestamp, external_id, slack_channel_id):
    '''
    Get the ID of the service a Slack channel is integrated to.
    :param conn: db connection
    :param timestamp: timestamp when this request is being made
    :param external_id: slack team ID
    :param slack_channel_id: the Slack channel ID
    :return: (tuple) -> (organization ID, service ID, integration ID, external info)
    '''
    assert isinstance(timestamp, datetime.datetime)
    assert isinstance(external_id, str)
    assert isinstance(slack_channel_id, str)

    query = '''
            select organization_id, serviceid, integration_id, access_token, vendor_endpoint, oitd.details
            from service_integrations as sint
            join organization_integration_type_details as oitd using(organization_id, integration_type_id)
            where sint.start_timestamp <= %(timestamp)s
                and sint.end_timestamp > %(timestamp)s
                and sint.additional_info->>'channel_id' = %(chn_id)s
                and sint.integration_type_id in (
                    select integration_type_id from integration_types
                    where start_date <= %(timestamp)s
                        and end_date > %(timestamp)s
                        and integration_type = %(slack_type)s
                )
                and oitd.start_timestamp <= %(timestamp)s
                and oitd.end_timestamp > %(timestamp)s
                and oitd.external_id = %(ext_id)s;
            '''
    query_params = {'timestamp': timestamp, 'ext_id': external_id,
                    'chn_id': slack_channel_id, 'slack_type': integration_type_names.slack}
    try:
        result = conn.fetch(query, query_params)
        for org_id, serv_id, integ_id, acc_token, slack_hook, ext_info in result:
            return org_id, serv_id, integ_id, acc_token, slack_hook, ext_info

        return None, None, None, None
    except psycopg2.DatabaseError:
        raise
