from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from datetime import *
import csv
import re
from django.utils import simplejson

class Command(BaseCommand):
    args = '<filename>'

    @transaction.commit_on_success
    def handle(self, *args, **options):
        from django.db import models
        from pycon.core import safe_ascii_encode
        if len(args) != 1:
            raise CommandError('give a filename')

        try:
            models = models.get_app('schedule')
        except (ImproperlyConfigured, ImportError), e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        from pycon.feedutil.templatetags.feedutil import pull_feed
        vm = dict((e['data']['blip_item_id'], (e['url'], e['data'].get('blip_smallthumbnail', ''), e['data']['media_player'], e['data']['title']))
                    for e in pull_feed("http://pycon.blip.tv/rss"))
        vm.update(dict((e['data']['blip_item_id'], (e['url'], e['data'].get('blip_smallthumbnail', ''), e['data']['media_player'], e['data']['title']))
                    for e in pull_feed("http://pycon.blip.tv/rss?page=0")))
        vm.update(dict((e['data']['blip_item_id'], (e['url'], e['data'].get('blip_smallthumbnail', ''), e['data']['media_player'], e['data']['title']))
                    for e in pull_feed("http://pycon.blip.tv/rss?page=1")))
        vm.update(dict((e['data']['blip_item_id'], (e['url'], e['data'].get('blip_smallthumbnail', ''), e['data']['media_player'], e['data']['title']))
                    for e in pull_feed("http://pycon.blip.tv/rss?page=2")))
        vm.update(dict((e['data']['blip_item_id'], (e['url'], e['data'].get('blip_smallthumbnail', ''), e['data']['media_player'], e['data']['title']))
                    for e in pull_feed("http://pycon.blip.tv/rss?page=3")))

        print "loaded", len(vm), "videos from blip rss"

        connect = simplejson.load(file(args[0], 'U'))
        print "loaded", len(connect), "videos from the connect json file"

        missing = []
        for videoevent in connect:
            vid = videoevent['fields']['target']
            if vid is None: continue
            if vid in vm:
                eid = videoevent['fields']['primary']
                if not eid:
                    print "Skipping bad field: %r" % videoevent['fields']
                    continue
                vurl = vm[vid][0]
                e = models.Event.objects.get(pk=int(eid, 10))
                vl = models.VideoLink.objects.get_or_create(event=e, url=vurl)[0]
                vl.vid = vid
                vl.thumb = vm[vid][1]
                vl.code = vm[vid][2]
                vl.save()
                #print "Connected:", vid
            else:
                print "Not in feed yet?:", vid, videoevent['fields']['name']
                missing.append((videoevent['fields']['name'], videoevent))

        if missing:
            print "Second Pass search for %d missing videos" % len(missing)
            vmbt = dict((e[3], (e, k)) for k, e in vm.iteritems())
            vmbtl = vmbt.keys()
            for name, videoevent in missing:
                found = None
                for check in vmbtl:
                    if name in check:
                        found = check
                        break
                if found is None:
                    print "Still missing: ", videoevent['fields']['name']
                    continue
                eid = videoevent['fields']['primary']
                e = models.Event.objects.get(pk=int(eid, 10))
                vme, vid = vmbt[found]
                vl = models.VideoLink.objects.get_or_create(event=e, url=vurl)[0]
                vl.vid = vid
                vl.thumb = vme[1]
                vl.code = vme[2]
                vl.save()
                #print "Found And Connected:", vid, videoevent['fields']['name']
