# Path: golem/core/interfaces/adapter/microsoft.py
# class MicrosoftAdapter():
#     def __init__(self, chat_id):
#         self.chat_id = chat_id
# 
#     def to_response(self, element) -> dict:
#         if isinstance(element, MessageElement):
#             if isinstance(element, TextMessage):
#                 response = {"text": element.text}
# 
#                 if element.quick_replies:
#                     response["suggestedActions"] = {"actions": self.quick_replies(element.quick_replies)}
#                 elif element.buttons:
#                     response["suggestedActions"] = {"actions": self.buttons(element.buttons)}
# 
#                 return response
#             elif isinstance(element, GenericTemplateMessage) or isinstance(element, ListTemplate):
#                 return self.generic_template(element)
#                 # TODO cards and lists
# 
#         return {"text": str(element)}
# 
#     def quick_replies(self, replies):
#         return [{
#             "type": "imBack",
#             "title": q.title,
#             "value": q.title
#         } for q in replies]
# 
#     def buttons(self, buttons):
#         arr = []
#         for btn in buttons:
#             if isinstance(btn, LinkButton):
#                 arr.append({
#                     "type": "openUrl",
#                     "title": btn.title,
#                     "value": btn.url
#                 })
#             elif isinstance(btn, PayloadButton):
#                 arr.append({
#                     "type": "postBack",
#                     "title": btn.title,
#                     "value": btn.payload
#                 })
#             elif isinstance(btn, PhoneButton):
#                 arr.append({
#                     "type": "call",
#                     "title": btn.title,
#                     "value": btn.phone_number
#                 })
#                 # TODO other buttons
#         return arr
# 
#     def generic_template(self, template: GenericTemplateMessage or ListTemplate):
#         if isinstance(template, GenericTemplateMessage):
#             content_type = "application/vnd.microsoft.card.hero"
#         elif isinstance(template, ListTemplate):
#             content_type = "application/vnd.microsoft.card.thumbnail"
#         else:
#             raise Exception('Invalid template parameter')
#         response = {
#             "attachments": [
#                 {
#                     "contentType": content_type,
#                     "content": {
#                         "title": elem.title,
#                         # "subtitle": elem.subtitle,
#                         "text": elem.subtitle[:1000],
#                         "images": [{
#                             "url": elem.image_url,
#                             "alt": "event picture",
#                             "tap": {
#                                 "type": "openUrl",
#                                 "value": elem.item_url
#                             }
#                         }],
#                         "buttons": self.buttons(elem.buttons)
#                     }
#                 }
#                 for elem in template.elements
#             ]
#         }
#         return response
# 
# Path: golem/core/message_parser.py
# def parse_text_message(text, num_tries=1):
#     if len(ENTITY_EXTRACTORS) <= 0:
#         logging.warning('No entity extractors configured!')
#         return {'type': 'message', 'entities': {'_message_text': [{'value': text}]}}
# 
#     entities = {}
# 
#     for extractor in ENTITY_EXTRACTORS:
#         append = extractor.extract_entities(text)
#         for entity, values in append.items():
#             entities.setdefault(entity, []).extend(values)
# 
#     logging.debug('Extracted entities:', entities)
#     append = parse_additional_entities(text)
# 
#     for (entity, value) in re.findall(re.compile(r'/([^/]+)/([^/]+)/'), text):
#         if not entity in append:
#             append[entity] = []
#         append[entity].append({'value': value})
# 
#     # add all new entity values
#     for entity, values in append.items():
#         if not entity in entities:
#             entities[entity] = []
#         entities[entity] += values
# 
#     entities['_message_text'] = [{'value': text}]
# 
#     parsed = {'entities': entities, 'type': 'message'}
# 
#     return parsed
# 
# Path: golem/core/persistence.py
# def get_redis():
#     global _connection_pool
#     global _redis
#     if not _connection_pool:
#         config = settings.GOLEM_CONFIG.get('REDIS')
#         _connection_pool = redis.ConnectionPool(
#             host=config['HOST'],
#             port=config['PORT'],
#             password=config['PASSWORD'],
#             db=0,
#             max_connections=2
#         )
#     if not _redis:
#         _redis = redis.StrictRedis(connection_pool=_connection_pool)
#     return _redis
# 
# Path: golem/tasks.py
# @shared_task
# def accept_user_message(session: dict, raw_message):
#     from golem.core.dialog_manager import DialogManager
#     session = ChatSession.from_json(session)
#     print("Accepting message - chat id {}, message: {}".format(session.chat_id, raw_message))
# 
#     dialog = DialogManager(session)
#     parsed = session.interface.parse_message(raw_message)
#     _process_message(dialog, parsed)
# 
#     should_log_messages = settings.GOLEM_CONFIG.get('SHOULD_LOG_MESSAGES', False)
# 
#     if should_log_messages and 'text' in raw_message:
#         text = raw_message['text']
#         message_logger.on_message.delay(session, text, dialog, from_user=True)
#     return True  # FIXME


import json
import logging
import requests
from datetime import datetime, timedelta
from typing import Optional
from django.conf import settings
from golem.core.interfaces.adapter.microsoft import MicrosoftAdapter
from golem.core.message_parser import parse_text_message
from golem.core.persistence import get_redis
from golem.tasks import accept_user_message




# FIXME needs to be updated

class MicrosoftInterface():
    name = 'microsoft'
    prefix = 'ms'

    @staticmethod

# Path: golem/core/interfaces/adapter/microsoft.py
# class MicrosoftAdapter():
#     def __init__(self, chat_id):
#         self.chat_id = chat_id
# 
#     def to_response(self, element) -> dict:
#         if isinstance(element, MessageElement):
#             if isinstance(element, TextMessage):
#                 response = {"text": element.text}
# 
#                 if element.quick_replies:
#                     response["suggestedActions"] = {"actions": self.quick_replies(element.quick_replies)}
#                 elif element.buttons:
#                     response["suggestedActions"] = {"actions": self.buttons(element.buttons)}
# 
#                 return response
#             elif isinstance(element, GenericTemplateMessage) or isinstance(element, ListTemplate):
#                 return self.generic_template(element)
#                 # TODO cards and lists
# 
#         return {"text": str(element)}
# 
#     def quick_replies(self, replies):
#         return [{
#             "type": "imBack",
#             "title": q.title,
#             "value": q.title
#         } for q in replies]
# 
#     def buttons(self, buttons):
#         arr = []
#         for btn in buttons:
#             if isinstance(btn, LinkButton):
#                 arr.append({
#                     "type": "openUrl",
#                     "title": btn.title,
#                     "value": btn.url
#                 })
#             elif isinstance(btn, PayloadButton):
#                 arr.append({
#                     "type": "postBack",
#                     "title": btn.title,
#                     "value": btn.payload
#                 })
#             elif isinstance(btn, PhoneButton):
#                 arr.append({
#                     "type": "call",
#                     "title": btn.title,
#                     "value": btn.phone_number
#                 })
#                 # TODO other buttons
#         return arr
# 
#     def generic_template(self, template: GenericTemplateMessage or ListTemplate):
#         if isinstance(template, GenericTemplateMessage):
#             content_type = "application/vnd.microsoft.card.hero"
#         elif isinstance(template, ListTemplate):
#             content_type = "application/vnd.microsoft.card.thumbnail"
#         else:
#             raise Exception('Invalid template parameter')
#         response = {
#             "attachments": [
#                 {
#                     "contentType": content_type,
#                     "content": {
#                         "title": elem.title,
#                         # "subtitle": elem.subtitle,
#                         "text": elem.subtitle[:1000],
#                         "images": [{
#                             "url": elem.image_url,
#                             "alt": "event picture",
#                             "tap": {
#                                 "type": "openUrl",
#                                 "value": elem.item_url
#                             }
#                         }],
#                         "buttons": self.buttons(elem.buttons)
#                     }
#                 }
#                 for elem in template.elements
#             ]
#         }
#         return response
# 
# Path: golem/core/message_parser.py
# def parse_text_message(text, num_tries=1):
#     if len(ENTITY_EXTRACTORS) <= 0:
#         logging.warning('No entity extractors configured!')
#         return {'type': 'message', 'entities': {'_message_text': [{'value': text}]}}
# 
#     entities = {}
# 
#     for extractor in ENTITY_EXTRACTORS:
#         append = extractor.extract_entities(text)
#         for entity, values in append.items():
#             entities.setdefault(entity, []).extend(values)
# 
#     logging.debug('Extracted entities:', entities)
#     append = parse_additional_entities(text)
# 
#     for (entity, value) in re.findall(re.compile(r'/([^/]+)/([^/]+)/'), text):
#         if not entity in append:
#             append[entity] = []
#         append[entity].append({'value': value})
# 
#     # add all new entity values
#     for entity, values in append.items():
#         if not entity in entities:
#             entities[entity] = []
#         entities[entity] += values
# 
#     entities['_message_text'] = [{'value': text}]
# 
#     parsed = {'entities': entities, 'type': 'message'}
# 
#     return parsed
# 
# Path: golem/core/persistence.py
# def get_redis():
#     global _connection_pool
#     global _redis
#     if not _connection_pool:
#         config = settings.GOLEM_CONFIG.get('REDIS')
#         _connection_pool = redis.ConnectionPool(
#             host=config['HOST'],
#             port=config['PORT'],
#             password=config['PASSWORD'],
#             db=0,
#             max_connections=2
#         )
#     if not _redis:
#         _redis = redis.StrictRedis(connection_pool=_connection_pool)
#     return _redis
# 
# Path: golem/tasks.py
# @shared_task
# def accept_user_message(session: dict, raw_message):
#     from golem.core.dialog_manager import DialogManager
#     session = ChatSession.from_json(session)
#     print("Accepting message - chat id {}, message: {}".format(session.chat_id, raw_message))
# 
#     dialog = DialogManager(session)
#     parsed = session.interface.parse_message(raw_message)
#     _process_message(dialog, parsed)
# 
#     should_log_messages = settings.GOLEM_CONFIG.get('SHOULD_LOG_MESSAGES', False)
# 
#     if should_log_messages and 'text' in raw_message:
#         text = raw_message['text']
#         message_logger.on_message.delay(session, text, dialog, from_user=True)
#     return True  # FIXME


# Path: golem/core/interfaces/microsoft.py
import json
import logging
import requests
from datetime import datetime, timedelta
from typing import Optional
from django.conf import settings
from golem.core.interfaces.adapter.microsoft import MicrosoftAdapter
from golem.core.message_parser import parse_text_message
from golem.core.persistence import get_redis
from golem.tasks import accept_user_message





# FIXME needs to be updated

class MicrosoftInterface():
    name = 'microsoft'
    prefix = 'ms'

    @staticmethod

    def get_base_url(chat_id) -> Optional[str]: