import json
import os
import logging
import urllib
import boto3
import time
import decimal
import googletrans


print('Loading function')
# BOT_TOKEN = os.environ["BOT_TOKEN"]

alarm_ssm = boto3.client('ssm')


def _read_bot_token():
    ssm_result = alarm_ssm.get_parameter(
        Name='BOT_TOKEN'
    )
    return ssm_result.get('Parameter').get('Value')


def _read_slack_url():
    ssm_result = alarm_ssm.get_parameter(
        Name='SLACK_URL'
    )
    return ssm_result.get('Parameter').get('Value')


def _verify_token(token):
    ssm_result = alarm_ssm.get_parameter(
        Name='VERIFICATION_TOKEN'
    )
    if ssm_result.get('Parameter').get('Value') == token:
        return True
    else:
        return False


def send_slack_message(event, context):
    body = {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "input": event
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response

    # Use this code if you don't use the http event with the LAMBDA-PROXY
    # integration
    """
    return {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "event": event
    }
    """


def get_historical_messages(event, context):

    logging.warn(json.dumps(event))
    body = {
        "hello": "world"
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response


def slack_event_handler(event, context):

    if "body" in event:
        print("Found body, reading as json")
        body = json.loads(event['body'])
        if "challenge" in body:
            print("Found challenge, object: " + json.dumps(body))
            response = {
                "statusCode": 200,
                "body": body["challenge"]
            }
            return response

    if 'body' in event:
        slack_event = json.loads(event['body'])
        print("Found body, reading as json. Object: " + json.dumps(slack_event))

    if _verify_token(slack_event['token']):

        # We need to discriminate between events generated by
        # the users, which we want to process and handle,
        # and those generated by the bot.
        if "bot_id" in slack_event['event']:
            print("BOT_ID found - Not continuing")
            body = {
                "result": "Failed, BOT_ID included"
            }

        else:
            print("BOT_ID not found - Continuing")
            
            text = slack_event['event']['text']
            
            translator = googletrans.Translator()
            translated_text = translator.translate(text).text
            
            response = translated_text
            
            # # Get the text of the message the user sent to the bot,
            # # and reverse it.
            #
            # text = slack_event['event']['text']
            # reversed_text = text[::-1]
            #
            # # Get the ID of the channel where the message was posted.
            # channel_id = slack_event['event']["channel"]

            # We need to send back three pieces of information:
            #     1. The reversed text (text)
            #     2. The channel id of the private, direct chat (channel)
            #     3. The OAuth token required to communicate with
            #        the API (token)
            # Then, create an associative array and URL-encode it,
            # since the Slack API doesn't not handle JSON (bummer).
            data = urllib.parse.urlencode(
                (
                    ("token", _read_bot_token()),
                    ("channel", channel_id),
                    ("text", response)
                )
            )
            data = data.encode("ascii")

            # Construct the HTTP request that will be sent to the Slack API.
            request = urllib.request.Request(
                _read_slack_url(),
                data=data,
                method="POST"
            )
            # Add a header mentioning that the text is URL-encoded.
            request.add_header(
                "Content-Type",
                "application/x-www-form-urlencoded"
            )

            # Fire off the request!
            urllib.request.urlopen(request).read()
            body = {
                "result": "Success, message sent"
            }

    else:
        body = {
            "result": "Failed to verify message"
        }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response
