#!/usr/bin/env python

import datetime
import feedparser
import json
import os
from urlparse import urlparse

def readConfigFile():
    """Read the config file ~/.youtube-rss and return a dictionary"""
    path = os.path.expanduser("~/.youtube-rss")
    configFile = open(path)
    contents = configFile.read()
    configFile.close()
    return json.loads(contents)

def saveConfigFile(dictonary):
    """Take a dictonary and save it to the config file as json"""
    newContents = json.dumps(dictonary, sort_keys=True, indent=4)
    path = os.path.expanduser("~/.youtube-rss")
    configFile = open(path, "w")
    configFile.write(newContents)
    configFile.close()

def getVideoIdFromUrl(url):
    urlparts = urlparse(url)
    args = urlparts.query.split("&")
    for arg in args:
        pair = arg.split("=")
        if pair[0] == "v":
            return pair[1]

    return None

def downloadVid(vidId, path):
    if path[-1] != '/':
        path = "%s/" % path

    now = datetime.datetime.now()

    sysCall = "youtube-dl -o \"%s%s_%%(stitle)s.%%(ext)s\" \"http://www.youtube.com/watch?v=%s\"" % \
        (path, now.strftime("%Y-%m-%d"), vidId)

    os.system(sysCall)

def checkForNew(channel):
    feed = feedparser.parse(channel['link'])
    for entry in feed.entries:
        vidId = getVideoIdFromUrl(entry.link)
        if vidId not in channel['watched']:
            fullpath = os.path.expanduser(channel['destination'])
            downloadVid(vidId, fullpath)
            channel['watched'].append(vidId)

    return channel

def main():
    """Downloads all the links"""
    config = readConfigFile()
    newconfig = []
    for channel in config:
        newconfig.append(checkForNew(channel))

    saveConfigFile(newconfig)

if __name__ == "__main__":
    main()