'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()

app.set('port', (process.env.PORT || 5000))

app.use(bodyParser.urlencoded({extended: false}))

app.use(bodyParser.json())


app.get('/', function (req, res) {
	res.send('Hello world, I am a chat bot')
})

app.get('/webhook/', function (req, res) {

	if (req.query['hub.verify_token'] === 'bot_me') {
		res.send(req.query['hub.challenge'])
	}
	res.send('Error, wrong token')
})

app.listen(app.get('port'), function() {
	console.log('running on port', app.get('port'))
})

app.post('/webhook/', function (req, res) {
    let messaging_events = req.body.entry[0].messaging
    for (let i = 0; i < messaging_events.length; i++) {
	    let event = req.body.entry[0].messaging[i]
	    let sender = event.sender.id
	    if (event.message && event.message.text) {
		    let text = event.message.text
		    sendTextMessage(sender, "Hi am Neha :) ,Happy to Respond")
	    }
    }
    res.sendStatus(200)
})

function sendTextMessage(sender, text) {
    let messageData = { text:text }
    request({
	    url: 'https://graph.facebook.com/v2.6/me/messages',
	    qs: {access_token:token},
	    method: 'POST',
		json: {
		    recipient: {id:sender},
			message: messageData,
		}
	}, function(error, response, body) {
		if (error) {
		    console.log('Error sending messages: ', error)
		} else if (response.body.error) {
		    console.log('Error: ', response.body.error)
	    }
    })
}


const token = "EAAOm6OD7imQBAMA9tRNe2egKS2w3ZCDIlkWw1U66Ap9vEDkVpXU612KoP2mDgh3laayJBvYyc7q6gPlTZAYUztW5BUNYCkjjnQkgtPlXM2eOuZCD5A1bHztsX2s736Mq9FoYkid5ZBXOSlbnb6ZAtZCD6bKzAZBrCxOfcRJEImu1AZDZD"