import select, logging, traceback

from lcm import LCM

logger = logging.getLogger(__name__)

class Subscriber():
    def __init__(self, channel_list, msg_handler):
        self._lcm = LCM("udpm://239.255.76.67:7667?ttl=55")
        self._subscription_list = []
        for channel in channel_list:
            self._subscription_list.append(self._lcm.subscribe(channel, msg_handler))

        self._fd = self._lcm.fileno()
        
    def __enter__(self):
        return self


    def __exit__(self, type, value, tb):
        if type or value or tb:
            traceback.print_exception(type, value, tb)
        logger.debug('In LCM __exit__.')
        self.close()
        return False # rethrow
    

    def get(self):
        (fd_list,dum,dum) = select.select([self._fd],[],[],0)
        if fd_list:
            self._lcm.handle()
            return True
        else:
            return False


    def close(self):
        for sub in self._subscription_list:
            self._lcm.unsubscribe(sub)


class Publisher():
    def __init__(self):
        self._lcm = LCM()

    
    def __enter__(self):
        return self


    def __exit__(self, type, value, traceback):
        pass


    def publish(self, channel, msg):
        self._lcm.publish(channel, msg.encode())
