# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from datatypes_date_time.timex import Timex

from botbuilder.dialogs import WaterfallDialog, WaterfallStepContext, DialogTurnResult
from botbuilder.dialogs.prompts import ConfirmPrompt, TextPrompt, PromptOptions
from botbuilder.core import MessageFactory
from botbuilder.schema import InputHints
from .cancel_and_help_dialog import CancelAndHelpDialog
from botbuilder.schema import ChannelAccount, CardAction, ActionTypes, SuggestedActions


class faq(CancelAndHelpDialog):
    def __init__(self, dialog_id: str = None):
        super(faq, self).__init__(dialog_id or faq.__name__)

        self.add_dialog(TextPrompt(TextPrompt.__name__))
        self.add_dialog(ConfirmPrompt(ConfirmPrompt.__name__))
        self.add_dialog(
            WaterfallDialog(
                WaterfallDialog.__name__,
                [
                    self.first_step, self.final_step, self.end_step
                ],
            )
        )

        self.initial_dialog_id = WaterfallDialog.__name__

    async def first_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        Complete the interaction and end the dialog.
        :param step_context:
        :return DialogTurnResult:
        """
        reply = MessageFactory.text("please ask your question")
        return await step_context.prompt(
            TextPrompt.__name__, PromptOptions(prompt=reply)
        )

    async def final_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        Complete the interaction and end the dialog.
        :param step_context:
        :return DialogTurnResult:
        """
        await step_context.context.send_activity(self.api_hit(str(step_context.result)))
        reply = MessageFactory.text("Are there any other questions I should answer?")
        reply.suggested_actions = SuggestedActions(
            actions=[
                CardAction(
                    title="Yes",
                    type=ActionTypes.im_back,
                    value='yes'
                ),
                CardAction(
                    title="No",
                    type=ActionTypes.im_back,
                    value='no'
                )
            ]
        )
        return await step_context.prompt(
            TextPrompt.__name__, PromptOptions(prompt=reply)
        )

    async def end_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
        """
        Complete the interaction and end the dialog.
        :param step_context:
        :return DialogTurnResult:
        """
        if str(step_context.result).lower() == 'yes':
            return await step_context.replace_dialog(self.id)
        await step_context.context.send_activity("hope I was able to answer all your questions")
        return await step_context.end_dialog()

    def is_ambiguous(self, timex: str) -> bool:
        timex_property = Timex(timex)
        return "definite" not in timex_property.types

    def api_hit(self, question):
        import requests

        url = "https://ilens-assistant-qna.azurewebsites.net/qnamaker/knowledgebases/0697399a-4050-4f19-80ce-4ad8dae41b6a/generateAnswer"

        payload = "{\"question\":\"" + question + "\"}"
        print(payload)
        headers = {
            'Authorization': 'EndpointKey 031de099-2a8b-4b27-af84-2a5e15b35413',
            'Content-Type': 'application/json',
            'Cookie': 'ARRAffinity=05b4cef5a3f30849a8768536ff665c720ef1b15f35ff9c5d7fa3f54b9d6f9375; ARRAffinitySameSite=05b4cef5a3f30849a8768536ff665c720ef1b15f35ff9c5d7fa3f54b9d6f9375'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        print(response.text)
        my_ans = response.json()
        print(my_ans["answers"][0]["answer"])
        return str(my_ans["answers"][0]["answer"])
