#!/usr/bin/env python

import combine
import feeds
import os
import persistent
from scrapy.crawler import CrawlerProcess
from scrapy.settings import Settings
import settings
from tornado.platform.twisted import TwistedIOLoop
import tornado.web


TwistedIOLoop().install()

full_settings = Settings()
full_settings.setmodule(settings)

process = CrawlerProcess(full_settings)
crawler = persistent.Crawler(full_settings)
process.crawl(crawler)


class HomeHandler(tornado.web.RequestHandler):
    def get(self):
        try:
            feed = self.get_argument("feed")
        except tornado.web.MissingArgumentError:
            git_rev = os.environ.get("GIT_REV") or "unknown"
            self.render("home.html", git_rev=git_rev)
        else:
            url = self.reverse_url("read", feed)
            self.redirect(url)


class FeedHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self, feed):
        try:
            entries = yield feeds.full_history(crawler, feed)
        except feeds.FeedError as exc:
            self.set_status(400)
            self.render("feed-error.html", feed=feed, message=str(exc))
            return

        self.set_header("Content-Type", "text/plain")
        for e in entries:
            self.write("{}\t{}\n".format(e["source"], e["id"]))
        self.finish()


application = tornado.web.Application(
    [
        (r"/$", HomeHandler, {}, "home"),
        (r"/history/(.+)", FeedHandler),
        (r"/read/(.+)", combine.ExportHandler, {"crawler": crawler}, "read"),
        (r"/page/([^/]+)/(.+)", combine.PageHandler, {"crawler": crawler}, "page"),
        (r"/entry/([^/]+)/(.+)", combine.EntryHandler, {"crawler": crawler}, "entry"),
    ],
    static_path="static/",
    template_path="templates/",
    debug="PRODUCTION" not in os.environ,
)
application.listen(int(os.environ.get("PORT", 8888)))

process.start()
