# Path: bitsd/listener/notifier.py
# def send_message(text):
# def send_status(value):
# def send_sound(soundid):
# 
# Path: bitsd/persistence/engine.py
# @contextmanager
# def session_scope():
#     """Provide a transactional scope around a series of operations."""
#     session = Session()
#     try:
#         yield session
#         session.commit()
#     except IntegrityError as e:
#         LOG.error("Integrity error in DB, rolling back: %s", e)
#         session.rollback()
#     except:
#         LOG.error("Error in DB, rolling back.")
#         session.rollback()
#         raise
#     finally:
#         session.close()
# 
# Path: bitsd/persistence/models.py
# class Status(Base):
#     """Representation of a logged status change."""
#     __tablename__ = 'Status'
#     __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8mb4'}
# 
#     OPEN = 'open'
#     CLOSED = 'closed'
#     AWAY = 'away'
# 
#     timestamp = Column(DateTime, primary_key=True, default=datetime.now)
#     value = Column(
#         Enum(OPEN, CLOSED, AWAY),
#         nullable=False
#     )
#     modified_by = Column(Enum('BITS', 'web'), nullable=False)
# 
#     def __init__(self, value, modified_by):
#         self.value = value
#         self.modified_by = modified_by
# 
#     def __str__(self):
#         return 'Status {.value}'.format(self)
# 
#     def jsondict(self, wrap=True):
#         """Return a JSON-serializable dictionary representing the object"""
#         data = {
#             "timestamp": self.timestamp.isoformat(' '),
#             "modifiedby": self.modified_by,
#             "value": self.value
#         }
#         if wrap:
#             return {'status': data}
#         else:
#             return data
# 
# Path: bitsd/common.py
# LOG = logging.getLogger('tornado.general')


import base64
import bitsd.persistence.query as query
from bitsd.listener import notifier
from bitsd.persistence.engine import session_scope
from bitsd.persistence.models import Status
from bitsd.common import LOG
def handle_message_command(message):
    """Handles message broadcast requests."""
    LOG.info('Received message command: message=%r', message)
    try:
        decodedmex = base64.b64decode(message)
    except TypeError:
        LOG.error('Received message is not valid base64: %r', message)
    else:
        text = decodedmex.decode('utf8')
        #FIXME maybe get author ID from message?
        user = "BITS"
        with session_scope() as session:
            user = query.get_user(session, user)
            if not user:
                LOG.error("Non-existent user %r, not logging message.", user)
                return
            message = query.log_message(session, user, text)
            broadcast(message.jsondict())
        notifier.send_message(text)


def handle_sound_command(soundid):
    """Handles requests to play a sound."""
    LOG.info('Received sound command: id=%r', soundid)
    try:
        soundid = int(soundid)
    except ValueError:
        LOG.error('Wrong type for parameters in temperature command!')
        return
    else:

# Path: bitsd/listener/notifier.py
# def send_message(text):
# def send_status(value):
# def send_sound(soundid):
# 
# Path: bitsd/persistence/engine.py
# @contextmanager
# def session_scope():
#     """Provide a transactional scope around a series of operations."""
#     session = Session()
#     try:
#         yield session
#         session.commit()
#     except IntegrityError as e:
#         LOG.error("Integrity error in DB, rolling back: %s", e)
#         session.rollback()
#     except:
#         LOG.error("Error in DB, rolling back.")
#         session.rollback()
#         raise
#     finally:
#         session.close()
# 
# Path: bitsd/persistence/models.py
# class Status(Base):
#     """Representation of a logged status change."""
#     __tablename__ = 'Status'
#     __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8mb4'}
# 
#     OPEN = 'open'
#     CLOSED = 'closed'
#     AWAY = 'away'
# 
#     timestamp = Column(DateTime, primary_key=True, default=datetime.now)
#     value = Column(
#         Enum(OPEN, CLOSED, AWAY),
#         nullable=False
#     )
#     modified_by = Column(Enum('BITS', 'web'), nullable=False)
# 
#     def __init__(self, value, modified_by):
#         self.value = value
#         self.modified_by = modified_by
# 
#     def __str__(self):
#         return 'Status {.value}'.format(self)
# 
#     def jsondict(self, wrap=True):
#         """Return a JSON-serializable dictionary representing the object"""
#         data = {
#             "timestamp": self.timestamp.isoformat(' '),
#             "modifiedby": self.modified_by,
#             "value": self.value
#         }
#         if wrap:
#             return {'status': data}
#         else:
#             return data
# 
# Path: bitsd/common.py
# LOG = logging.getLogger('tornado.general')


# Path: bitsd/listener/hooks.py
import base64
import bitsd.persistence.query as query
from bitsd.listener import notifier
from bitsd.persistence.engine import session_scope
from bitsd.persistence.models import Status
from bitsd.common import LOG

def handle_message_command(message):
    """Handles message broadcast requests."""
    LOG.info('Received message command: message=%r', message)
    try:
        decodedmex = base64.b64decode(message)
    except TypeError:
        LOG.error('Received message is not valid base64: %r', message)
    else:
        text = decodedmex.decode('utf8')
        #FIXME maybe get author ID from message?
        user = "BITS"
        with session_scope() as session:
            user = query.get_user(session, user)
            if not user:
                LOG.error("Non-existent user %r, not logging message.", user)
                return
            message = query.log_message(session, user, text)
            broadcast(message.jsondict())
        notifier.send_message(text)


def handle_sound_command(soundid):
    """Handles requests to play a sound."""
    LOG.info('Received sound command: id=%r', soundid)
    try:
        soundid = int(soundid)
    except ValueError:
        LOG.error('Wrong type for parameters in temperature command!')
        return
    else:

        notifier.send_sound(soundid)