# -*- coding: utf-8 -*-
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.utils.datetime_safe import datetime

from events.models import Event, Location
import xlrd


class Command(BaseCommand):
    help = "Importiert die alten Events"  # @ReservedAssignment

    def __init__(self):
        self.author = get_user_model().objects.get(username="xeniac")
        super(Command, self).__init__()

    def handle(self, *args, **options):
        try:
            xls_file = xlrd.open_workbook(args[0])
        except IndexError:
            return "Bitte den Pfad zur Excel Datei angeben!"
        except IOError:
            return "Datei '%s' wurde nicht gefunden! " % args[0]

        table = xls_file.sheet_by_index(0)
        for row in xrange(1, table.nrows):
            name = table.cell_value(row, 0)
            print name

            start = xlrd.xldate_as_tuple(table.cell_value(row, 1),
                                         xls_file.datemode)
            start = datetime(start[0], start[1], start[2], 0, 0, 0)

            end = xlrd.xldate_as_tuple(table.cell_value(row, 2),
                                       xls_file.datemode)
            end = datetime(end[0], end[1], end[2], 23, 59, 59)

            location = Location.objects.get(pk=table.cell_value(row, 3))

            Event.objects.get_or_create(name=name, start=start, defaults={
                'end': end,
                'location': location,
            })
