from edu.sc.seis.fissuresUtil.flow import Receiver, Message
from edu.sc.seis.fissuresUtil.flow.querier import EventFinderQuery
from edu.sc.seis.fissuresUtil.database.event import JDBCEventAccess
from edu.sc.seis.fissuresUtil.database import NotFound
from gee.SenderBase import SenderBase

class EventDB(Receiver, SenderBase):
    def __init__(self, receiver=None):
        SenderBase.__init__(self, receiver=receiver)
        self.db = JDBCEventAccess()
        self.query = EventFinderQuery()
        
    def _clearcache(self):
        if 'events' in self.__dict__: del self.events

    def __setattr__(self, name, value):
        if name == 'query': self._clearcache()
        self.__dict__[name] = value

    def __getattr__(self, name):
        if name == 'events':
            self.events = [self.db.getEvent(id) for id in self.db.query(self.query)]
            return self.events

    def receive(self, message):
        if not self.db.contains(message.subject):
            self.db.insert(message.subject, '', '', '')
            self._clearcache()
            if self.query.test(message.subject).passed():
                self.send(message)

    def __contains__(self, o):
        return o in self.events

    def __len__(self):
        return len(self.events)

    def __iter__(self):
        return self.events.__iter__()

    def __getitem__(self, key):
        return self.events[key]