from urllib2 import Request, urlopen
import json
import os

bot_token = os.environ['BOT_TOKEN']
bot_name = os.environ['BOT_NAME']
bot_email = os.environ['BOT_EMAIL']

url = 'https://api.ciscospark.com/v1/messages/'
json_header = {"Accept" : "application/json","Content-Type":"application/json"}

def lambda_handler(event, context):
    
    # The 'event' function input parameter is the json payload in the Spark API HTTP POST call 
    # when a message is generated in the Spark room
    
    # Retrieve the Spark room message text via a HTTP GET request using the "'data' { 'id' }" value 
    # in the incoming json payload
    
    msg_url = url+event['data']['id']
    get_sparkroom_msg = Request(msg_url, headers=json_header)
    get_sparkroom_msg.add_header("Authorization", "Bearer " + bot_token)
    response = urlopen(get_sparkroom_msg).read()
    result = json.loads(response)
  
    # Ignore Spark room messages generated by the bot itself to avoid creating a message loop
    # Format the Spark room message to lowercase and strip the bot name from the text
  
    if event['data']['personEmail'] != bot_email:
        in_message = result['text'].lower()
        in_message = in_message.replace(bot_name, '')

        # If the Spark room message text is 'joke' then HTTP GET a joke from the Chuck Norris DB
        # and POST that joke into the Spark room

        if 'joke' in in_message:
            request = Request('http://api.icndb.com/jokes/random')
            joke_read = urlopen(request).read()
            sep = joke_read.split("joke")
            sep1 = sep[1].split("\"")
            joke = sep1[2].replace("&quot;", "'")
            request = Request(url, json.dumps({"roomId": event['data']['roomId'] , "text": joke}), headers=json_header)
            request.add_header("Authorization", "Bearer " + bot_token)
            response = urlopen(request).read()
        
    return "true"

