

# -*- coding:utf8 -*-
# !/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()

from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError

import json
import os
import requests
import pysnow

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)

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


def processRequest(req):
    if req.get("result").get("action") == "yahooWeatherForecast":
        baseurl = "https://query.yahooapis.com/v1/public/yql?"
        yql_query = makeYqlQuery(req)
        if yql_query is None:
            return {}
        yql_url = baseurl + urlencode({'q': yql_query}) + "&format=json"
        result = urlopen(yql_url).read()
        data = json.loads(result)
        res = makeWebhookResult(data)
    elif req.get("result").get("action") == "getjoke":
        baseurl = "http://api.icndb.com/jokes/random"
        result = urlopen(baseurl).read()
        data = json.loads(result)
        res = makeWebhookResultForGetJoke(data)
    elif req.get("result").get("action") == "test":
        #result = requests.get('https://dev24188.service-now.com/api/now/table/sys_user?', auth=('admin', 'nK010595!'))
        #data = json.loads(result.text)
        res = makeWebhookResultForGetEmail(req)
    else:
        return {}

    return res

def makeWebhookResultForGetEmail(req):
    result = req.get("result")
    parameters = result.get("parameters")
    full_name = parameters.get("name")
    pin_type = parameters.get("Pin_Type")

    request_url = requests.get('https://dev49509.service-now.com/api/now/table/sys_user?name=' + full_name, auth=('admin', 'nr0HP1bAcQoO'))
    data = json.loads(request_url.text)

    #User DOES NOT exist in servicenow database
    if data['result'] == []:
        speechText = "Sorry, I can't seem to find you in our database. Are you sure you work for us? LOL"
        displayText = "Sorry, I can't seem to find you in our database. Are you sure you work for us? LOL"
    #User DOES exist in database
    else:
        data = json.loads(request_url.text)
        email = data['result'][0]['email']
        first_name = data['result'][0]['first_name']
        last_name = data['result'][0]['last_name']

        c = pysnow.Client(instance='dev49509', user='admin', password="nr0HP1bAcQoO")
        incident = c.resource(api_path='/table/incident')
        new_record = {
            'caller_id': full_name,
            'short_description': full_name + " requires a pin reset for his " + pin_type,
            'description': "Pretty please work",
            #'opened_by': "The Magical Leprechaun",
            #'u_pin_reset_ty': pin_type,
            #'assigned_to': "The Magical Leprechaun"
        }

        incident.create(payload=new_record)

        # result = data.get('result')
        speechText = "Thanks " + first_name + ", I've logged your request for a new " + pin_type + \
                      " pin. You will receive an email with a unique 5 digit pin and instructions on " \
                      "how to reset it! If you have any other queries or issues with" \
                      " this incident, please call GTS on 01 123 4567"
        displayText = "Thanks " + first_name + ", I've logged your request for a new " + pin_type + \
                      " pin. You will receive an email with a unique 5 digit pin and instructions on " \
                      "how to reset it! If you have any other queries or issues with" \
                      " this incident, please call GTS on 01 123 4567"

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

def makeWebhookResultForGetJoke(data):
    valueString = data.get('value')
    joke = valueString.get('joke')
    speechText = joke
    displayText = joke
    return {
        "speech": speechText,
        "displayText": displayText,
        # "data": data,
        # "contextOut": [],
        "source": "apiai-weather-webhook-sample"
    }

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 the weather in " + location.get('city') + ": " + condition.get('text') + \
             ", And 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')
