#!/usr/bin/python
# coding: utf-8

from datetime import date
from datetime import timedelta
from optparse import OptionParser
from feedcircuit.feedcircuit import Feed
from feedcircuit.feedcircuit import Item
from feedcircuit.hildonui import Program
import locale
import os

locale.setlocale(locale.LC_ALL, '')
report_progress = True


def update_callback(item):
	if report_progress:
		print item[0], item[1]


parser = OptionParser("usage: %prog [options] url1 url2 ...")
parser.add_option("-p", "--path", help = "path to store feed", dest = "path", default = "")
parser.add_option("-s", "--single-page", help = "transform single html page", \
	action = "store_true", dest = "single", default = False)
parser.add_option("-c", "--cache", help = "cache items", \
	action = "store_true", dest = "cache", default = False)
parser.add_option("-i", "--inline", help = "inline items", \
	action = "store_true", dest = "inline", default = False)
parser.add_option("-g", "--ignore-print-version", help = "ignore link to the printable version", \
	action = "store_false", dest = "use_print_version", default = True)
parser.add_option("-q", "--quiet", help = "do not report any progress to the stdout", \
	action = "store_false", dest = "report_progress", default = True)
parser.add_option("-d", "--days-to-keep", help = "days to keep news", \
	type = "int", dest = "days_to_keep")
parser.add_option("-a", "--allow-scripts", help = "do not remove scripts from pages", \
	action = "store_true", dest = "allow_scripts", default = False)
parser.add_option("--include", help = "regexp for urls to include to the feed", dest = "include")
parser.add_option("--exclude", help = "regexp for urls to exxlude from the feed", dest = "exclude")
(options, args) = parser.parse_args()

if len(args) == 0:
    if os.environ.has_key("DISPLAY") and os.environ["DISPLAY"]:
        app = Program()
        app.run()
    else:
	    print "please specify feed url(s)"
else:
    report_progress = options.report_progress

    delete_before_date = None
    if options.days_to_keep:
    	delete_before_date = date.today() - timedelta(options.days_to_keep)

    if options.single:
    	for arg in args:
    		item = Item(url = arg, path = options.path, cache_path = ".cache", callback = update_callback, \
    			try_use_print_version = options.use_print_version, allow_scripts = options.allow_scripts)
    		item.process()
    		item.save(filename = item.title + ".html")
    else:
    	for arg in args:
    		feed = Feed(arg, path = options.path, inline_items = options.inline, cache_items = options.cache, \
    			try_use_print_version = options.use_print_version, allow_scripts = options.allow_scripts, \
    			delete_before_date = delete_before_date, callback = update_callback, cache_path = ".cache",
    			include = options.include, exclude = options.exclude)
    		feed.update()

