"""
Import a rooms division file
Format:

name, divided, parent1, parent2, parentN
"""
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

def line2entry(line):
    if len(line.strip()) == 0: return (None, None, None)
    parts = [ e.strip() for e in line.split(',') ]
    name = parts.pop(0)
    divided = bool(parts.pop(0))
    return name, divided, parts

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('Enter a valid input file.')
        try:
            models = models.get_app('schedule')
        except (ImproperlyConfigured, ImportError), e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        cache = {}
        for room, div, parents in (line2entry(l) for l in file(args[0],'rU')):
            if room == None: break
            robj, new = models.Room.objects.get_or_create(name=room)
            print 'room', room
            robj.divided = div
            robj.save()
            if parents:
                robj.parents = [ cache[name] for name in parents ]
                robj.save()
            cache[room]=robj
