from ploneintranet.notifications.sql import saconfig
from Products.Five import BrowserView


class InitDBView(BrowserView):
    def __call__(self):
        session = saconfig.session()
        saconfig.Base.metadata.create_all(session.bind.engine, checkfirst=True)
        self.request.response.setHeader("Content-Type", "text/plain")
        return "OK"


class SchedulerView(BrowserView):
    @property
    def logged_events(self):
        """Get all the unprocessed logged events."""
        return saconfig.session.query(saconfig.LoggedEvent).filter(
            saconfig.LoggedEvent.processed == None  # noqa: E711
        )

    def create_notifications(self):
        for logged_event in self.logged_events:
            logged_event.notify_all()

    def __call__(self):
        self.create_notifications()
        self.request.response.setHeader("Content-Type", "text/plain")
        return "OK"
