#!/usr/bin/env python

from optparse import OptionParser
import os
import urllib
import urllib2
from xml.dom import minidom

__version__ = 1.1

statusMap = {
              'New Series'      : '_NEW_SERIES_',
              'Canceled/Ended'  : '_ENDED_',
              'Returning Series': '_RETURNING_',
             }

def loadMapFile():
    global showdirToIdMap
    
    # Read the show map (name -> id)
    log('Reading map file...')
    showdirToIdMap = dict()
    f = open(options.mapFile, 'r')
    for line in f.readlines():
        (key, sep, val) = line.partition(':')
        showdirToIdMap[key.strip().lower()] = val.strip()
    f.close()

def getFeed(id):
    params = urllib.urlencode({'sid' : id })
    r = urllib2.Request(url='http://services.tvrage.com/feeds/showinfo.php?%s' % params)
    r.add_header('User-Agent', 'StatusFetcher %s' % __version__)
    log('  Fetching %s' % r.get_full_url())
    response = urllib2.urlopen(r)
    data = response.read()
    response.close()
    return data

def getStatus(feed):
    xmldoc = minidom.parseString(feed)
    nodelist = xmldoc.getElementsByTagName('status')
    if nodelist == None:
        log("Can't find node 'status'")
    elif len(nodelist) != 1:
        log('Incorrect number of nodes %d' % len(nodelist))
    else:
        rc = []
        for node in nodelist[0].childNodes:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)
    return 'N/A'

def updateStatusDirectory(archivepath, showdir):
    showpath = os.path.join(archivepath, showdir)
    statusdir = None

    showdirkey = showdir.lower()

    if showdirkey in showdirToIdMap:
        showid = showdirToIdMap[showdirkey]
        log('  ID is %s' % showid)

        feed = getFeed(showid)
        status = getStatus(feed)

        log('  Status is %s' % status)
        if status in statusMap:
            statusdir = statusMap[status]
            log('  Statusdir is %s' % statusdir)

            # Remove old status directories
            for tmpdir in statusMap.values():
                tmp = os.path.join(showpath, tmpdir)
                if tmpdir != statusdir and os.path.isdir(tmp):
                    log('  Removing old status dir %s' % tmpdir)
                    os.rmdir(tmp)

            # Create status directory unless it already exist
            tmp = os.path.join(showpath, statusdir)
            if not os.path.isdir(tmp):
                os.mkdir(tmp)
    else:
        log('Skipping non mapped show %s' % showdir)
    
def log(str):
    if options.verbose:
        print str        

def main():
    global options

    parser = OptionParser('%prog <-m mapfile> <path> [, path]*', version='%prog 1.0')
    parser.add_option('-m', '--map-file', dest='mapFile',
                      help='Map file to read')
    parser.add_option('-v', '--verbose',
                      action='store_true', dest='verbose')
    (options, args) = parser.parse_args()

    if options.mapFile == None or not os.path.isfile(options.mapFile):
        parser.error('Missing mapfile')

    if len(args) == 0:
        parser.error('incorrect number of args')
    
    loadMapFile()
    
    for archive in args:
        if os.path.isdir(archive):
            log('Handling directory %s' % archive)
            for showdir in os.listdir(archive):
                log('Show %s' % showdir)
                updateStatusDirectory(archive, showdir)
        else:
            log('Skipping non existing directory %s' % archive)

if __name__ == '__main__':
    main()

