import os
from lxml import etree

# write_rss_xml writes name and date data for podcast RSS feeds to XML files
# contained in the relative path ./feeds. It is currently assumed that each
# podcast will have its data stored in a separate file.
def write_rss_xml( feed, feed_url, latest_title, latest_date ):

    # the function currently assumes that the storage location will be
    
file_path = "feeds"
    feed_name = feed
    file_name = feed_name + "_rss.xml"

    # Open the file to write binary data. write_rss_xml will currently only
    # operate by re-writing the xml file every time; this will be improved in
    # a later version.
    with open(os.path.join(file_path, file_name), "wb") as write_file:

        # root of lxml ElementTree
        root = etree.Element("podcast")

        # subElements of root. Right now there should only be four of these,
        # corresponding to the podcast name, feed url, latest episode name, and
        # latest episode date.

        pageElement = etree.SubElement(root, "name").text = feed_name
        pageElement = etree.SubElement(root, "url").text = feed_url
        pageElement = etree.SubElement(root, "episode").text = latest_title
        pageElement = etree.SubElement(root, "date").text = latest_date

        # Create a string from the ElementTree with pretty print and necessary
        # encoding, for printing to file.
        out_xml = etree.tostring(root, xml_declaration=True, pretty_print=True)

        # Print the string out_xml to the file whose name is contained in the
        # variable file_name.
        write_file.write(out_xml)


    write_file.close()