#!/usr/bin/python
from albatross import SimpleSessionApp, SessionAppContext
from albatross.cgiapp import Request
import popviewlib


class LoginPage:

    name = 'login'

    def page_process(self, ctx):
        if ctx.req_equals('login'):
            if ctx.locals.username and ctx.locals.passwd:
                try:
                    ctx.open_mbox()
                    ctx.add_session_vars('username', 'passwd')
                except poplib.error_proto:
                    return
                ctx.set_page('list')

    def page_display(self, ctx):
        ctx.run_template('login.html')


class ListPage:

    name = 'list'

    def page_process(self, ctx):
        if ctx.req_equals('msgnum'):
            ctx.set_page('detail')

    def page_display(self, ctx):
        ctx.open_mbox()
        ctx.run_template('list.html')


class DetailPage:

    name = 'detail'

    def page_process(self, ctx):
        if ctx.req_equals('list'):
            ctx.set_page('list')

    def page_display(self, ctx):
        ctx.open_mbox()
        ctx.read_msg()
        ctx.run_template('detail.html')


class AppContext(SessionAppContext):

    def open_mbox(self):
        if hasattr(self.locals, 'mbox'):
            return
        self.locals.mbox = popviewlib.Mbox(self.locals.username, self.locals.passwd)

    def read_msg(self):
        if hasattr(self.locals, 'msg'):
            return
        self.locals.msg = self.locals.mbox[int(self.locals.msgnum) - 1]
        self.locals.msg.read_body()


class App(SimpleSessionApp):

    def __init__(self):
        SimpleSessionApp.__init__(self,
                                  base_url='popview.py',
                                  template_path='.',
                                  start_page='login',
                                  secret='-=-secret-=-',
                                  session_appid='popview3')
        for page_class in (LoginPage, ListPage, DetailPage):
            self.register_page(page_class.name, page_class())

    def create_context(self):
        return AppContext(self)


app = App()


if __name__ == '__main__':
    app.run(Request())
