import tornado.ioloop
import tornado.web
import tornado.template
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)

import os.path as os_path
import logging as log

import crispin


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MailboxHandler),
            (r"/mailbox", MailboxHandler),
            (r"/thread", MessageThreadHandler),
            (r"/message", MessagePageHandler),
            (r"/message_raw", MessageRawHandler),
            # (r"/(apple-touch-icon\.png)", tornado.web.StaticFileHandler,
            # (r"/(apple-touch-icon\.png)", tornado.web.StaticFileHandler,
        ]
        settings = dict(
            cookie_secret="awehofoiasdfhsadkfnwem42rwfubksfj",
            login_url="/auth/login",
            template_path=os_path.join(os_path.dirname(__file__), "templates"),
            static_path=os_path.join(os_path.dirname(__file__), "static"),
            xsrf_cookies=True,
            debug=True,
        )
        tornado.web.Application.__init__(self, handlers, **settings)


class BaseHandler(tornado.web.RequestHandler):
    pass


class MainHandler(BaseHandler):

    def get(self):
        loader = tornado.template.Loader("templates/")
        home_template = loader.load("base.html")
        self.write(home_template.generate(emails=[]))


class MessagePageHandler(BaseHandler):

    def get(self):
        try:
            crispin.connect()
            crispin.select_folder("Inbox")
        except Exception, e:
            self.send_error(500)
            raise e

        uid = crispin.latest_message_uid()
        msg = crispin.fetch_msg(uid)

        page_width = self.get_argument("page_width", '600')
        page_width = int(page_width)

        self.render("singlethread.html",
                    to_name = msg.to_contacts[0]['name'],
                    to_addr = msg.to_contacts[0]['address'],
                    from_name = msg.from_contacts[0]['name'], 
                    from_addr = msg.from_contacts[0]['address'],
                    sent_time = msg.date.strftime('%b %m, %Y &mdash; %I:%M %p'),
                    subject = msg.subject,
                    headers = [],
                    sender_gravatar_url = msg.gravatar() )


class MessageRawHandler(BaseHandler):
    def get(self):
        crispin.connect()
        crispin.select_allmail_folder() # anywhere

        msg_id = self.get_argument("msg_id", default=None, strip=False)

        if not msg_id:
            msg_id = crispin.latest_message_uid()
            log.warning("No msg_id passed in. Using latest message id: %s" % msg_id)
        else:
            log.info("Passed in msg_id %s", msg_id)
        
        msg = crispin.fetch_msg(msg_id)

        latest_message_raw = msg.body_text
        self.render("message.html", 
            raw_msg_data = latest_message_raw)



class MailboxHandler(BaseHandler):
    def get(self):

        folder_name = self.get_argument("folder", default="Inbox", strip=False)
        log.info('Opening folder:' + str(folder_name))
        
        # Todo: Do this for every setup somehow.
        if not(crispin.connect()):
            log.error("Couldn't connect. Proably offline right now.")
            self.send_error(500)
            return

        crispin.select_folder("Inbox")

        threads = crispin.fetch_threads(folder_name)
        threads.sort(key=lambda t: t.most_recent_date(), reverse=True)

        # subjs = []
        # for m in new_messages:
        #     s = m.trimmed_subject()
        #     if not s in subjs:
        #         subjs.append(s)

        self.render("mailbox.html", 
                    threads = threads)



class MessageThreadHandler(BaseHandler):
    def get(self):

        thread_id = self.get_argument("thread_id", default=None, strip=False)
        if not thread_id:
            self.send_error(500)
            return

        crispin.connect()

        select_info = crispin.select_allmail_folder()
        msg_ids = crispin.fetch_thread(thread_id)

        log.info("selected thread_id: %s which has msg_ids: %s" % (thread_id, msg_ids) )

        self.render("thread.html", 
            thread_ids = msg_ids)

        


def main():
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)

    if (app.settings['debug']):
        tornado.autoreload.start()

    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()

@@ -225,22 +225,64 @@
 og%0A%0A
-import crispin
+from crispin import CrispinClient%0A%0Acrispin_client = None
 %0A%0A%0Ac
@@ -1534,38 +1534,15 @@
 spin
-.connect()%0A            crispin
+_client
 .sel
@@ -1657,32 +1657,39 @@
    uid = crispin
+_client
 .latest_message_
@@ -1707,32 +1707,39 @@
    msg = crispin
+_client
 .fetch_msg(uid)%0A
@@ -2420,34 +2420,15 @@
 spin
-.connect()%0A        crispin
+_client
 .sel
@@ -2584,16 +2584,23 @@
  crispin
+_client
 .latest_
@@ -2790,24 +2790,31 @@
 sg = crispin
+_client
 .fetch_msg(m
@@ -3202,24 +3202,26 @@
 how.%0A       
+ #
  if not(cris
@@ -3235,32 +3235,34 @@
 nect()):%0A       
+ #
      log.error(%22
@@ -3307,32 +3307,34 @@
 t now.%22)%0A       
+ #
      self.send_e
@@ -3342,32 +3342,34 @@
 ror(500)%0A       
+ #
      return%0A%0A   
@@ -3372,32 +3372,39 @@
 %0A        crispin
+_client
 .select_folder(%22
@@ -3429,32 +3429,39 @@
 hreads = crispin
+_client
 .fetch_threads(f
@@ -4005,35 +4005,8 @@
 rn%0A%0A
-        crispin.connect()%0A%0A
     
@@ -4030,16 +4030,23 @@
  crispin
+_client
 .select_
@@ -4087,16 +4087,23 @@
  crispin
+_client
 .fetch_t
@@ -4399,16 +4399,80 @@
 .port)%0A%0A
+    global crispin_client%0A    crispin_client = CrispinClient()%0A%0A
     if (

Use new crispin refactor.