from flask import Flask, request
app = Flask(__name__)
import json
import requests
from database.db import Db
from responseBuilder import ResponseBuilder
from messageEntity import MessageEntity



class MessageHandler:
    db = Db()

    def buildResponseForRequest(self, payload):

        messaging = payload["entry"][0]["messaging"]
        timestamp = payload["entry"][0]["time"]

        for event in messaging:
            if "message" in event and "text" in event["message"]:
                messagesender = event["sender"]
                messagetext = event["message"]["text"]
                print 'sender: ', messagesender, ' text: ', messagetext'
                messageEntity = MessageEntity(messagesender, messagetext)
                self.db.storeIncomingMsg(messagesender, messagetext, timestamp)

                responses = responsebuilder.getResponsesForMessage(messageEntity)
                if responses:
                    return {'messagesender' : messagesender, 'responsetext' : responses[0]["responseText"], 'timestamp': timestamp}
                else:
                    return False


    def sendResponse(self, response, token):
        r = requests.post("https://graph.facebook.com/v2.6/me/messages",
        params={"access_token": token},
        data=json.dumps({
            "recipient": {"id": response.messagesender},
            "message": {"text": response.responsetext}
        }),
        headers={'Content-type': 'application/json'})
    if r.status_code != requests.codes.ok:
        print 'request codes not ok:', r.text
    else:
        print 'response done, inserting outgoing msg into db'
        self.db.storeOutgoingMsg(response.messagesender, response.responsetext, response.timestamp)

@@ -225,16 +225,56 @@
 b = Db()
+%0A    responsebuilder = ResponseBuilder()
 %0A%0A    de
@@ -563,16 +563,22 @@
 sender%22%5D
+%5B%22id%22%5D
 %0A       
@@ -696,17 +696,16 @@
 sagetext
-'
 %0A       
@@ -880,16 +880,21 @@
 onses = 
+self.
 response
@@ -1520,16 +1520,20 @@
 json'%7D)%0A
+    
     if r
@@ -1567,32 +1567,36 @@
 des.ok:%0A        
+ 
+   
 print 'request c
@@ -1617,30 +1617,38 @@
  r.text%0A    
+  
+  
 else:%0A
+    
         prin
@@ -1697,16 +1697,20 @@
 nto db'%0A
+    
         

fix msg sender index and indent bugs