# 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/core/interfaces/test.py
# class TestInterface():
#     name = 'test'
#     prefix = 'test'
#     messages = []
#     states = []
# 
#     @staticmethod
#     def clear():
#         TestInterface.messages = []
#         TestInterface.states = []
# 
#     @staticmethod
#     def fill_session_profile(session: ChatSession):
#         if not session:
#             raise ValueError("Session is None")
#         session.profile = Profile(first_name='Test', last_name='')
#         return session
# 
#     @staticmethod
#     def post_message(session, response):
#         TestInterface.messages.append(response)
# 
#     @staticmethod
#     def send_settings(settings):
#         pass
# 
#     @staticmethod
#     def processing_start(session):
#         pass
# 
#     @staticmethod
#     def processing_end(session):
#         pass
# 
#     @staticmethod
#     def state_change(state):
#         if not TestInterface.states or TestInterface.states[-1] != state:
#             TestInterface.states.append(state)
# 
#     @staticmethod
#     def parse_message(user_message, num_tries=1):
#         return user_message
# 
# 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/serialize.py
# def json_deserialize(obj):
#     #print('Deserializing:', obj)
#     from golem.core.entities import Entity
#     if obj.get('__type__') == 'datetime':
#         return dateutil.parser.parse(obj.get('value'))
#     elif obj.get('__type__') == 'entity':
#         bytearr = str.encode(obj.get("__data__"))
#         return pickle.loads(b64decode(bytearr))
#     return obj
# 
# 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']
#         )


import json
import logging
import time
import random
from golem.core.persistence import get_redis
from golem.core.responses.responses import *
from golem.core.responses.buttons import *
from django.conf import settings
from .interfaces.test import TestInterface
from .message_parser import parse_text_message
from .serialize import json_deserialize
from .chat_session import ChatSession
        from .dialog_manager import DialogManager
            from .dialog_manager import DialogManager



class ConversationTestException(Exception):
    def __init__(self, message):
        super(ConversationTestException, self).__init__(message)

class UserMessage:
    def get_parsed(self):
        pass

class UserTextMessage(UserMessage):
    def __init__(self, text):
        self.text = text
        self.entities = {}

    def produces_entity(self, entity, value = None):
        self.entities[entity] = value
        return self

    def get_parsed(self):
        TestLog.log('Sending user message "{}".'.format(self.text))

# 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/core/interfaces/test.py
# class TestInterface():
#     name = 'test'
#     prefix = 'test'
#     messages = []
#     states = []
# 
#     @staticmethod
#     def clear():
#         TestInterface.messages = []
#         TestInterface.states = []
# 
#     @staticmethod
#     def fill_session_profile(session: ChatSession):
#         if not session:
#             raise ValueError("Session is None")
#         session.profile = Profile(first_name='Test', last_name='')
#         return session
# 
#     @staticmethod
#     def post_message(session, response):
#         TestInterface.messages.append(response)
# 
#     @staticmethod
#     def send_settings(settings):
#         pass
# 
#     @staticmethod
#     def processing_start(session):
#         pass
# 
#     @staticmethod
#     def processing_end(session):
#         pass
# 
#     @staticmethod
#     def state_change(state):
#         if not TestInterface.states or TestInterface.states[-1] != state:
#             TestInterface.states.append(state)
# 
#     @staticmethod
#     def parse_message(user_message, num_tries=1):
#         return user_message
# 
# 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/serialize.py
# def json_deserialize(obj):
#     #print('Deserializing:', obj)
#     from golem.core.entities import Entity
#     if obj.get('__type__') == 'datetime':
#         return dateutil.parser.parse(obj.get('value'))
#     elif obj.get('__type__') == 'entity':
#         bytearr = str.encode(obj.get("__data__"))
#         return pickle.loads(b64decode(bytearr))
#     return obj
# 
# 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/tests.py
import json
import logging
import time
import random
from golem.core.persistence import get_redis
from golem.core.responses.responses import *
from golem.core.responses.buttons import *
from django.conf import settings
from .interfaces.test import TestInterface
from .message_parser import parse_text_message
from .serialize import json_deserialize
from .chat_session import ChatSession
        from .dialog_manager import DialogManager
            from .dialog_manager import DialogManager




class ConversationTestException(Exception):
    def __init__(self, message):
        super(ConversationTestException, self).__init__(message)

class UserMessage:
    def get_parsed(self):
        pass

class UserTextMessage(UserMessage):
    def __init__(self, text):
        self.text = text
        self.entities = {}

    def produces_entity(self, entity, value = None):
        self.entities[entity] = value
        return self

    def get_parsed(self):
        TestLog.log('Sending user message "{}".'.format(self.text))

        parsed = parse_text_message(self.text)