# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007-2008 Toni Gundogdu
#
# clive is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 0.1.2-1307 USA
###########################################################################

## The classes for parsing rss/atom feeds

import urllib2

try:
    from clive.feedparser import feedparser as fparser
except ImportError, err:
    raise SystemExit('error: %s' % err)
try:
    from clive.newt import snack as newt
except ImportError, err:
    raise SystemExit('error: %s' % err)

__all__ = ['FeedParser']

## The feed parsing class
class FeedParser:

    ## Constructor
    def __init__(self, opts, say, proxy):
        self._opts = opts
        self._say = say
        self._proxy = proxy

    ## Reap feeds and display selection lists
    def parse(self, raw_urls):
        fparser.USER_AGENT = self._opts.http_agent
        h = urllib2.ProxyHandler(self._proxy)
        # Reap URLs
        feeds = []
        for url in raw_urls:
            self._say('feed: %s' % url)
            d = fparser.parse(url, handlers=[h])
            try:
                d.feed.title;
                feeds.append(d)
            except AttributeError:
                self._say('error: invalid rss/atom feed')
        # Display feeds and return user selection (video URLs)
        if len(feeds) == 0:
            raise SystemExit('error: no-data; check rss/atom urls')
        u = DisplayFeeds(feeds)
        return u.get_selection()


## The class that displays the feeds with found video URLs
class DisplayFeeds:

    ## Constructor
    def __init__(self, feeds):
        self._feeds = feeds
        self._selection = self._main()

    ## Returns the user selection of videos to be extracted
    def get_selection(self):
        return self._selection

    def _main(self):
        sel = []
        try:
            scr = newt.SnackScreen()
            sel = self._show_feeds(scr)
        finally:
            scr.finish()
        return sel

    def _show_feeds(self, scr):
        ct = newt.CheckboxTree(10, scroll=1)
        for (i,d) in enumerate(self._feeds):
            ct.append('%s (%d)' % (d.feed.title.encode('utf-8'), \
                len(d.entries)))
            for e in d.entries:
                ct.addItem(e.title.encode('utf-8'), 
                    (i, newt.snackArgs['append']), e.link.encode('utf-8'))
        g = newt.GridForm(scr, 'Select videos for extraction', 1,2)
        g.add(ct, col=0, row=0, padding=(0,0,0,1))
        b = newt.ButtonBar(scr, [('Cancel',0), ('OK',1)], compact=1)
        g.add(b, col=0, row=1, padding=(0,0,0,0))
        if not b.buttonPressed(g.runOnce()):
            raise SystemExit('Cancelled.')
        return ct.getSelection()
