## Copyright 2010, 2011, 2012 Tony Garnock-Jones <tonygarnockjones@gmail.com>.
##
## This file is part of Hop.
##
## Hop is free software: you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## Hop is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
## or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
## License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Hop.  If not, see <http://www.gnu.org/licenses/>.

import logging

class HopNode:
    def handle_hop(self, msg):
        raw_dispatch(self, 'hop_', msg)

    def error(self, message, details):
        logging.error('%r: %s: %r' % (self, message, details))

class HopRelayMixin:
    def inbound_hop(self, msg):
        raw_dispatch(self, 'inbound_hop_', msg)

def raw_dispatch(self, prefix, msg):
    if type(msg) is not list or len(msg) < 1:
        self.error('Invalid message', [])
        return

    raw_selector = msg[0]
    selector = prefix + raw_selector
    args = msg[1:]
    handler = getattr(self, selector, None)

    if not handler:
        self.error('Unsupported message or arity', [raw_selector])
        return

    try:
        handler(*args)
    except Exception:
        import traceback
        traceback.print_exc()
        self.error('Exception handling message', [raw_selector])
