#
# (c) 2009 Jeremy AustinBardo <tjaustinbardo AT gmail DOT com>
#
# This program 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; version 2 of the License.
#
# 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  02111-1307  USA
#
"""
SooVee Serial Audio Manger - Html pages with index for the forms module plugin. 
It will create a page for each serial audio feed in ./books and a link to it on
the index page.in the parent folder. 

This plugin was developed specificaly for soovee.gui summary view. It lacks the 
cover image and sets a few class attributes as well.

    - C{Format.write(filename:str, workstore:str, data:list, cache=None:obj, 
        rx=None:obj) -> None}
    - C{Format.item(item:dict, feed=None:dict, rx=None:obj) -> None}

@requires: soovee.lib.sv_Data
"""
METHOD = ("frm","view") #: Tuple of type and format
FILENAME = "index.html" #: Default file name for index


def write(filepath, workpath, data, cache=None, service=None):
    """
    Initialize and write set of html pages in ./books with an index. The 
    passed Opml data is used to retrieve the data for each Rss feed.

    @param filename: Local path-filename fragment.
    @type filename: basestring
    @param workstore: Base path-filename to store filename under.
    @type workstore: basestring
    @param data: List of Opml feed data to help build pages and locate Rss 
        feed data.
    @type data: list
    @param cache: Intialized soovee.lib.sv_read object. Default None.
    @type cache: obj
    @param rx: Intialized soovee.regex object. Default None.
    @type rx: obj
    @return:
    @rtype: None
    @requires: L{soovee.lib.sv_file}
    @raise TypeError: data passed was not a list
    """
    if not isinstance(data, list): 
        raise TypeError("FormsWrite missing list.")

    from soovee_lib.parse import Xml #: Rss data parsers

    fileobj_index = open(cache.mkpath(filepath=filepath, workpath=workpath), 
        "w")
    fileobj_index.write("<h1>Soovee Serial Audio feeds</h1>\n<ul>\n")

    for opml in data:
        yield opml['title']

        #{ Read data for feed page
        rss = Xml.rss(cache.Cache(opml['xmlUrl']).data())
        
        #{ Write data for feed page
        filename = cache.mkpath(filepath=service.TOHTM(opml['title']),
            workstore=workpath, subpath="books")
        fileobj_page = open(filename, "w")
        fileobj_page.write(
            item(opml, rss, service).encode("ascii", "xmlcharrefreplace")
            )
        fileobj_page.close()
        
        #{ Write data for feed page link to index page
        fileobj_index.write("<li><a href=\"%s\">%s</a><li>\n" % (
            filename, service.PRETITLE.sub("", opml['title'])))

    fileobj_index.write("</ul>\n")
    fileobj_index.close()


def item(data, feed=None, service=None ):
    """
    Format an html page for a feed subscription using data found in its Opml
    feed entry and in its Rss file. Store a filename for this page. Set 
    class attributes for use with soovee.gui summary view.

    @param item: Opml data
    @type item: dict
    @param feed: Rss data. Default dict.
    @type feed: dict
    @param rx: Intialized soovee.regex object. Default None.
    @type rx: obj
    @return:
    @rtype: basestring
    @raise TypeError: item or feed passed was not a dict
    """
    global pageUrl, imageUrl, feedTitle, encloseUrls

    if not isinstance(data, dict) and not isinstance(feed, dict): 
        raise TypeError("FormsItem missing dictionaries.")
    page = []

    feed['sum']['description'] = service.PRESUMMARY.sub(
        "", feed['sum']['description'])
    feed['sum']['category'] = feed['sum']['category'].split("; ")[2] #get 3rd
    #
    #{ Compose summary header data
    #
    page.append(
        ("<h1>%(title)s by %(itunes:author)s</h1><p><em>%(category)s</em>"
        "</p><p>%(description)s</p>") % feed['sum']
        )
    awards = service.GETIMAGES(data['description'])
    if awards:
        page.append(
            "<p>%s</p>" % "".join(
            [("<img src=\"%s\" />" % image) for image in awards]
            ))
    page.append("<hr />")

    #{ Format summary data fields from Rss Data <item>s
    for episode in feed['eps']:
        episode['encllength'] = service.TOMB(episode['enclosure']['length'])
        episode['enclurl'] = episode['enclosure']['url']
        episode['description'] = service.PREEPISODE.sub(
            "", episode['description'])
        page.append(
            ("<dt><a href=\"%(enclurl)s\">%(title)s</a>(%(encllength).2f MB"
            ")</dt><dd>%(description)s</dd>") % episode
            )
    return "".join(page)
