#!/usr/bin/env python
# -*- coding: utf-8 -*-

from microsoftbotframework import Response
import celery
import os
import sys
import json
# import argparse
from google.cloud import language
import google.auth
# import language

try:
    import apiai
except ImportError:
    sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
    import apiai

# CLIENT_ACCESS_TOKEN = 'd18b44be8d0b41269a42704c00d44d77'
CLIENT_ACCESS_TOKEN = '039129d3176644e9ac91464ee9e7b5df'


def respond_to_conversation_update(message):
    if message["type"] == "conversationUpdate":
        response = Response(message)
        message_response = 'Have fun with the Microsoft Bot Framework'
        response.reply_to_activity(message_response, recipient={"id": response["conversation"]["id"]})


def echo_response(message):
    if message["type"] == "message":
        response = Response(message)
        message_response = message["text"]
        # response_info = response.reply_to_activity("in this")
        # response_info = response.reply_to_activity(message_response)
        with open('intervention.json') as data_file:    
            iData = json.load(data_file)
            if iData["intervention"] == "0":
                ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
                request1 = ai.text_request()
                # request1.lang = 'en'  # optional, default value equal 'en'

                # request.session_id = "<SESSION ID, UBIQUE FOR EACH USER>"
                # print("\n\nYour Input : ",end=" ")
                # response.reply_to_activity(ai)

                with open('session.json') as data_file:    
                    data = json.load(data_file)
                    if data["session_id"] != "":
                        request1.session_id = data["session_id"]

                request1.query = message_response
                

                # request1.resetContexts = False
                # request1.
                # response_info = response.reply_to_activity("hello"+request1)

                # print("\n\nBot\'s response :",end=" ")
                response1 = request1.getresponse()
                responsestr = response1.read().decode('utf-8')
                response_obj = json.loads(responsestr)

                with open('session.json', 'w') as outfile:
                    json.dump({"session_id": response_obj["sessionId"]}, outfile)

                # print(response_obj["result"]["fulfillment"]["speech"])
                response_info = response.reply_to_activity(response_obj["result"]["fulfillment"]["speech"])



            else:
                with open('message.json') as data_file:    
                    data = json.load(data_file)
                    if data["message"] != "":
                        new_response = Response(data["message"])
                        # language_client = language.Client()
                        language_client = language.Client.from_service_account_json('Micro-av-bot-1.json')
                        # language_client = language.client

                        document = language_client.document_from_text(message_response)

                        # Detects sentiment in the document.
                        annotations = document.annotate_text(include_sentiment=True,
                                                             include_syntax=False,
                                                             include_entities=False)
                        score = annotations.sentiment.score
                        magnitude = annotations.sentiment.magnitude
                        # response_info = new_response.reply_to_activity('Overall Sentiment: score')
                        response_info = new_response.reply_to_activity('Overall Sentiment: score of {} with magnitude of {}'.format(score, magnitude))



                # response_info = response.reply_to_activity("Intervention is turned on")


#        from time import sleep

#        sleep(2)
#        response.delete_activity(activity_id=response_info.json()['id'])

#        sleep(2)
#        response.create_conversation('lets talk about something really interesting')


# This is a asynchronous task
@celery.task()
def echo_response_async(message):
    if message["type"] == "message":
        response = Response(message)
        message_response = message["text"]
        response.send_to_conversation(message_response)

