#!/usr/bin/env python

from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
import urllib.request, urllib.parse, urllib.error
import json
import os
import requests

from flask import Flask
from flask import request
from flask import make_response

# Flask app should start in global layout
app = Flask(__name__)


@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    #res = processRequest(req)
    speech = "Battery is running out mostly when you are playing games. Plus, turning  off your GPS  when it is not in use may help."
    res = {
        "speech": speech,
        "displayText": speech,
        # "data": data,
        # "contextOut": [],
        "source": "lg-assistant"
    }

    res = json.dumps(res, indent=4)
    # print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'

    sendFCM()

    return r


def sendFCM():
    url = 'https://fcm.googleapis.com/fcm/send'
    body = {
        "data":{
            "title":"mytitle",
            "body":"mybody",
            # "url":"myurl"
        },
        "notification":{
            "title":"Test title",
            "body":"Test body",
            "content_available": "true"
        },
        "to": "fqfSBcsFu7A:APA91bH8Ob2tgbirkUBAjPSwF4kZJGto5fFMousw8hRWo6AkutpIkFLauecEzSNUDtJoug92RJ7D1bVcq32rX5sWiIIKvNQwgZHswU2xIrYlsAS8BHrBQSvPuJVaV0117tqRwBn0dq1z"
    }

    headers = {"Content-Type":"application/json", "Authorization": "key=AAAAPll10tw:APA91bFgF4IU5k7V4-YBEphx9k7y7z0pqyhGcnN3Qbk8Wjuglftq8MzBa_ST75j4HSNh0YaonJov0BtTtq_85i8ao0Fm92JlDit96xLY5UJiC_OVwfFNvpYJnFU5FRYA7M8O20i2ahEi"}
    requests.post(url, data=json.dumps(body), headers=headers)
    return {}


def processRequest(req):
    if req.get("result").get("action") != "yahooWeatherForecast":
        return {}
    baseurl = "https://query.yahooapis.com/v1/public/yql?"
    yql_query = makeYqlQuery(req)
    if yql_query is None:
        return {}
    yql_url = baseurl + urllib.parse.urlencode({'q': yql_query}) + "&format=json"
    result = urllib.request.urlopen(yql_url).read()
    data = json.loads(result)
    res = makeWebhookResult(data)
    return res


def makeYqlQuery(req):
    result = req.get("result")
    parameters = result.get("parameters")
    city = parameters.get("geo-city")
    if city is None:
        return None

    return "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='" + city + "')"


def makeWebhookResult(data):
    query = data.get('query')
    if query is None:
        return {}

    result = query.get('results')
    if result is None:
        return {}

    channel = result.get('channel')
    if channel is None:
        return {}

    item = channel.get('item')
    location = channel.get('location')
    units = channel.get('units')
    if (location is None) or (item is None) or (units is None):
        return {}

    condition = item.get('condition')
    if condition is None:
        return {}

    # print(json.dumps(item, indent=4))

    speech = "__TODAY__ in " + location.get('city') + ": " + condition.get('text') + \
             ", the temperature is " + condition.get('temp') + " " + units.get('temperature')

    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": speech,
        # "data": data,
        # "contextOut": [],
        "source": "apiai-weather-webhook-sample"
    }


if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))

    print("Starting app on port %d" % port)

    app.run(debug=False, port=port, host='0.0.0.0')

@@ -1175,37 +1175,8 @@
 ody%22
-,%0A            # %22url%22:%22myurl%22
 %0A   
@@ -1567,17 +1567,16 @@
 zation%22:
- 
 %22key=AAA
@@ -1726,24 +1726,28 @@
 i2ahEi%22%7D%0A   
+ r =
  requests.po
@@ -1774,16 +1774,26 @@
 mps(body
+, indent=4
 ), heade
@@ -1804,16 +1804,29 @@
 eaders)%0A
+    print(r)%0A
     retu
@@ -1828,18 +1828,17 @@
  return 
-%7B%7D
+r
 %0A%0A%0Adef p

test FCM 6