#!/usr/bin/env python
#
# Copyright 2007 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
  vwt/message.py

  De/Serializeable message objects with Voluntary Weak Typesafety.
"""

import vwt

class Message(vwt.RepresentableObject): pass

class MessageInterpreter(object):

    """Register classes for de-serialization with evalMessage.

    A call to eval() needs a dictionary with all the class names
    needed to evaluate a message.  This class provides a convenient way
    to maintain such a dictionary.

    Example use:

       class MyMsg(Message):
           ...

       interpreter = MessageInterpreter(MyMsg, ....)
       obj = interpreter("MyMsg(...)")

    """

    def __init__(self, *args):
    
        """Construct a MessageInterpreter.

        Registers all classes listed to the constructor.
        """

        self._registered_message_classes = {}

        for arg in args:
            self.register(arg)

    def register(self, klass):
        "Register a message class with this MessageInterpreter"

        if type(klass) != type:
            raise TypeError("register: expected type object.")

        self._registered_message_classes[klass.__name__] = klass

    def __call__(self, msg):
        "Deserialize a message composed of registered classes."
        return eval(msg, self._registered_message_classes)

    def interpret(self, msg):
        "Try to deserialize a message, return None on any failure."
        try: return self.__call__(msg)
        except: return None
