# Path: golem/core/message_logger.py
# def on_message(uid, chat_id, message_text, dialog, from_user):
# 
# Path: golem/core/chat_session.py
# class ChatSession:
# 
#     def __init__(self, interface, unique_id: str, meta=None, profile=None, is_logged=True, is_admin=False, is_test=False):
#         """
#         :param interface: Chat interface object
#         :param unique_id: A string that uniquely identifies the user within the interface
#         :param profile: Profile object
#         :param meta: Any interface-specific data. type: dict
#         """
#         if interface is None:
#             raise ValueError("Interface must be set")
#         elif not isinstance(unique_id, str):
#             raise ValueError("UID must be a string")
#         elif not isinstance(profile, Profile) and profile is not None:
#             raise ValueError("Profile must be instance of class Profile")
#         self.interface = interface
#         self.chat_id = self.interface.prefix + "_" + unique_id
#         self.profile = profile or Profile()
#         self.meta = meta or {}
#         self.is_logged = is_logged
#         self.is_admin = is_admin
#         self.is_test = is_test
# 
#     def to_json(self):
#         return {
#             "interface": self.interface.prefix,
#             "unique_id": self.chat_id.split('_', maxsplit=1)[1],
#             "profile": self.profile.to_json(),
#             "meta": self.meta,
#             "is_logged": self.is_logged,
#             "is_admin": self.is_admin
#         }
# 
#     @staticmethod
#     def from_json(data: dict):
#         interface = create_from_prefix(data['interface'])
#         return ChatSession(
#             interface=interface,
#             unique_id=data['unique_id'],
#             profile=Profile.from_json(data['profile']),
#             meta=data['meta'],
#             is_logged=data['is_logged'],
#             is_admin=data['is_admin']
#         )
# 
# Path: golem/core/interfaces/all.py
# def create_from_name(name):
#     ifs = get_interfaces()
#     for interface in ifs:
#         if interface.name == name:
#             return interface
# 
# 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


import logging
import time
import traceback
    import json
from celery import shared_task
from celery.task.schedules import crontab
from celery.utils.log import get_task_logger
from django.conf import settings
from golem.core import message_logger  # this should register the celery log task
from golem.core.chat_session import ChatSession
from golem.core.interfaces.all import create_from_name
from golem.core.persistence import get_redis
    from golem.core.dialog_manager import DialogManager
    from golem.core.dialog_manager import DialogManager
    from golem.core.dialog_manager import DialogManager
    from golem.core.dialog_manager import DialogManager

    # User has sent a message, cancel inactivity callback
    if dialog.context.counter != context_counter:
        print('Canceling inactivity callback after user message.')
        return

    parsed = {
        'type': 'schedule',
        'entities': {
            'intent': '_inactive',
            '_inactive_seconds': inactive_seconds,
            '_callback_name': callback_name
        }
    }

    _process_message(dialog, parsed)


def _process_message(dialog, parsed):
    try:
        dialog.process(parsed['type'], parsed['entities'])
    except Exception as e:
        print("!!!!!!!!!!!!!!!! EXCEPTION AT MESSAGE QUEUE !!!!!!!!!!!!!!!", e)
        traceback.print_exc()
        dialog.logger.log_error(exception=e, state=dialog.current_state_name)


@shared_task
def fake_move_to_state(chat_id, state: str, entities=()):
    # TODO solve chat session saving and restoring

# Path: golem/core/message_logger.py
# def on_message(uid, chat_id, message_text, dialog, from_user):
# 
# Path: golem/core/chat_session.py
# class ChatSession:
# 
#     def __init__(self, interface, unique_id: str, meta=None, profile=None, is_logged=True, is_admin=False, is_test=False):
#         """
#         :param interface: Chat interface object
#         :param unique_id: A string that uniquely identifies the user within the interface
#         :param profile: Profile object
#         :param meta: Any interface-specific data. type: dict
#         """
#         if interface is None:
#             raise ValueError("Interface must be set")
#         elif not isinstance(unique_id, str):
#             raise ValueError("UID must be a string")
#         elif not isinstance(profile, Profile) and profile is not None:
#             raise ValueError("Profile must be instance of class Profile")
#         self.interface = interface
#         self.chat_id = self.interface.prefix + "_" + unique_id
#         self.profile = profile or Profile()
#         self.meta = meta or {}
#         self.is_logged = is_logged
#         self.is_admin = is_admin
#         self.is_test = is_test
# 
#     def to_json(self):
#         return {
#             "interface": self.interface.prefix,
#             "unique_id": self.chat_id.split('_', maxsplit=1)[1],
#             "profile": self.profile.to_json(),
#             "meta": self.meta,
#             "is_logged": self.is_logged,
#             "is_admin": self.is_admin
#         }
# 
#     @staticmethod
#     def from_json(data: dict):
#         interface = create_from_prefix(data['interface'])
#         return ChatSession(
#             interface=interface,
#             unique_id=data['unique_id'],
#             profile=Profile.from_json(data['profile']),
#             meta=data['meta'],
#             is_logged=data['is_logged'],
#             is_admin=data['is_admin']
#         )
# 
# Path: golem/core/interfaces/all.py
# def create_from_name(name):
#     ifs = get_interfaces()
#     for interface in ifs:
#         if interface.name == name:
#             return interface
# 
# 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
import logging
import time
import traceback
    import json
from celery import shared_task
from celery.task.schedules import crontab
from celery.utils.log import get_task_logger
from django.conf import settings
from golem.core import message_logger  # this should register the celery log task
from golem.core.chat_session import ChatSession
from golem.core.interfaces.all import create_from_name
from golem.core.persistence import get_redis
    from golem.core.dialog_manager import DialogManager
    from golem.core.dialog_manager import DialogManager
    from golem.core.dialog_manager import DialogManager
    from golem.core.dialog_manager import DialogManager


    # User has sent a message, cancel inactivity callback
    if dialog.context.counter != context_counter:
        print('Canceling inactivity callback after user message.')
        return

    parsed = {
        'type': 'schedule',
        'entities': {
            'intent': '_inactive',
            '_inactive_seconds': inactive_seconds,
            '_callback_name': callback_name
        }
    }

    _process_message(dialog, parsed)


def _process_message(dialog, parsed):
    try:
        dialog.process(parsed['type'], parsed['entities'])
    except Exception as e:
        print("!!!!!!!!!!!!!!!! EXCEPTION AT MESSAGE QUEUE !!!!!!!!!!!!!!!", e)
        traceback.print_exc()
        dialog.logger.log_error(exception=e, state=dialog.current_state_name)


@shared_task
def fake_move_to_state(chat_id, state: str, entities=()):
    # TODO solve chat session saving and restoring

    session = get_redis().hget("chat_session", chat_id)