import sys, os, urllib, sha
os.environ['DJANGO_SETTTINGS_MODULE'] = 'pycon.settings'
from pycon.schedule.models import *
from pycon.propmgr.models import *
from django.db import transaction
from django.contrib.auth.models import *
from datetime import *

from pycon import settings
print settings.__file__

room_map = {
    'Ballroom A-E': 1,
    'Ballroom F-J': 2,
    'Ballroom A-J': 3,
    'Mesquite': 4,
    'Preston Trail I+II+III': 5,
    }

sched06 = [
   # day   HH  MM    R  PRO  R  PRO  R  PRO
    (22, ( 10, 50, { 1:   6, 2:   7, 5:   8 } ),
         ( 11, 25, { 1:   9, 2:  10, 5:  11 } ),
         ( 12, 00, { 1:  12, 2:  13, 5:  14 } ),
         ( 13, 20, { 1:  15, 2:  16, 5:  17 } ),
         ( 14, 10, { 1:  18, 2:  19, 5:  20 } ),
         ( 15, 15, { 1:  21, 2:  22, 5:  23 } ),
         ( 15, 50, { 1:  24, 2:  25, 5:  26 } ),
         ( 16, 25, { 1:  27, 2:  28, 5:  29 } ), ),
        ]

room_cache = {}

def init_room_cache():
    print "Filling in room cache"
    for name, mapid in room_map.iteritems():
        room = Room.objects.get(name=name)
        room_cache[mapid] = room

@transaction.commit_on_success
def init_sched(year, month, sched):
    for daysched in sched:
        iterday = iter(daysched)
        day = iterday.next()
        print "Processing day:", day
        for slot in iterday:
            slottime = datetime(year=year, month=month, day=day,
                                hour=slot[0], minute=slot[1])
            print "Processing slot:", slottime
            for mapid, propid in slot[2].iteritems():
                room = room_cache[mapid]
                proposal = Proposal.objects.get(pk=propid)
                event = Event(proposal=proposal)
                event.save()
                sch = ScheduledEvent(event=event, start=slottime,
                                     room=room_cache[mapid])
                sch.save()


#if __name__ == '__main__':
#    init_room_cache()
#    init_sched(2006, 2, sched06)

import csv, re, os
propre = re.compile("^\d{3} ")
sched = [(2007, 2, 23, 'google-friday.csv'),
         (2007, 2, 24, 'google-saturday.csv'),
         (2007, 2, 25, 'google-sunday.csv')]

room_divisions = [
    # 'name',                divided, parents
    ('Addison',                False, None),
    ('Ballroom A-J',           True,  None),
    ('Ballroom A-E',           False, ['Ballroom A-J']),
    ('Ballroom F-J',           False, ['Ballroom A-J']),
    
    ('Mesquite',               True,  None),
    ('Mesquite I',             False, ['Mesquite']),
    ('Mesquite II',            False, ['Mesquite']),
    
    ('Preston Trail I+II+III', True,  None),
    ('Preston Trail I+II',     True,  None),
    ('Preston Trail II+III',   True,  None),
    ('Preston Trail I',        False, ['Preston Trail I+II+III',
                                       'Preston Trail I+II']),
    ('Preston Trail II',       False, ['Preston Trail I+II+III',
                                       'Preston Trail I+II',    
                                       'Preston Trail II+III']),
    ('Preston Trail III',      False, ['Preston Trail I+II+III',  
                                       'Preston Trail II+III']),
    
    ('Bent Tree I+II+III',     True,  None),
    ('Bent Tree I+II',         True,  None),
    ('Bent Tree II+III',       True,  None),
    ('Bent Tree I',            False, ['Bent Tree I+II+III',
                                       'Bent Tree I+II']),
    ('Bent Tree II',           False, ['Bent Tree I+II+III',
                                       'Bent Tree I+II',    
                                       'Bent Tree II+III']),
    ('Bent Tree III',          False, ['Bent Tree I+II+III',  
                                       'Bent Tree II+III']),
]

def timestr2datetime(year, month, day, timestr):
    # 11:25 am
    t, ap = timestr.split()
    hour, min = t.split(':')
    hour, min = int(hour,10), int(min,10)
    if ap == 'pm' and hour != 12: hour += 12
    return datetime(year=year, month=month, day=day,
                    hour=hour, minute=min)

def dur2dur(durstr):
    try:
        dur = int(durstr.split('+')[0], 10)
        if not dur: return 15
        return dur
    except:
        return 15

def talk2event(title, dur):
    if propre.match(title):
        pid=int(title[:3], 10)
        
        print "title", repr(title), "pid", pid
        prop=Proposal.objects.get(pk=pid)
        e = Event(proposal=prop)
        e.save()
        return e
    typ = 'E'
    if 'Lunch' in title: typ='B'
    if 'Break' in title: typ='B'
    if 'Plenary' in title: typ = 'P'
    if 'Meeting' in title: typ = 'M'
    e = Event(_summary="TBA", _title=title, _duration=dur2dur(dur), type=typ)
    e.save()
    return e

def importcsv(year, month, day, csvfile):
    reader = csv.reader(file(os.path.dirname(__file__) + '/' + csvfile))
    reader.next() ## title
    reader.next() ## blank line
    rooms = reader.next()[2:] ## rooms
    rooms = [ Room.objects.get(name=n) for n in rooms ]
    for line in reader:
        if len(line) < 3: break
        time, dur, talks = line[0], line[1], line[2:]
        dt = timestr2datetime(year, month, day, time)
        for ri, title in enumerate(talks):
            if not title: continue
            room = rooms[ri]
            event = talk2event(title, dur)
            if len(talks)==1 and event.type in ['P', 'B']: room = None
            sch = ScheduledEvent(event=event, start=dt, room=room)
            sch.save()
            print sch.start, sch.room, sch.event.type, sch.event.duration, sch

def importrooms():
    cache = {}
    for room, div, parents in room_divisions:
        robj, new = Room.objects.get_or_create(name=room) #, divided=div)
        print 'room', room
        robj.divided = div
        robj.save()
        if parents:
            robj.parents = [ cache[name] for name in parents ]
            robj.save()
        cache[room]=robj
    
@transaction.commit_on_success
def import_all():
    importrooms()
    for day in sched:
        importcsv(*day)

if __name__=='__main__':
    import_all()
