#!/usr/bin/python
# -*- coding: utf-8 -*-

import datetime

from openpyxl import Workbook


import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'ntuh.settings'
# from django.conf import settings
# settings.configure()
import django
django.setup()

from registry.models import *

def dt2time(d, t):
    # print(t.date)
    # print(d)
    if t.date() == d:
        return t.strftime('%H:%M')
    else:
        # return t.strftime('%m-%d %H:%M')
        return t.strftime('%H:%M(+1)')


week_day_dict = {
0 : '一',
1 : '二',
2 : '三',
3 : '四',
4 : '五',
5 : '六',
6 : '日',
}

ROOMS = set()

def format_last(d, l):
    ret= ['%s(%s)'%(d, week_day_dict[d.weekday()]), dt2time(d, l['last'])]
    rooms = l['rooms'] 

    # for r in sorted(rooms):
    #     ret.append('rm%d: %s'%(r, dt2time(d, rooms[r])))
    for r in sorted(ROOMS):
        if r in rooms:
            # ret.append('rm%d: %s'%(r, dt2time(d, rooms[r])))
            ret.append(dt2time(d, rooms[r]))
        else:
            ret.append('')

    return ret

LAST = {}


# for  op in  OPSchedule.objects.filter(OPDate__range=('2019-01-01', '2019-12-31')):
for  op in  OPSchedule.objects.filter(OpTypeName='預', OPDate__range=('2019-01-01', '2019-12-31')):

    ROOMS.add(op.OpRoomNo)

    begin = datetime.datetime.combine(op.OPDate,  op.StartTime)
    end = begin + datetime.timedelta(minutes=op.SpendTime)  

    # print(end)

    if op.OPDate not in LAST:
        rooms = {op.OpRoomNo: end}
        last = end
    else:
        l =  LAST[op.OPDate]
        rooms = l['rooms']
        last = l['last'] 

        if op.OpRoomNo not in rooms or  end > rooms[op.OpRoomNo]:
            rooms[op.OpRoomNo] = end

        if end > last:
            last = end

    LAST[op.OPDate] = {
            'rooms': rooms,
            'last': last,
        }


wb = Workbook()
ws = wb.active

row = ['', '']
for r in sorted(ROOMS):
    row.append('rm%s'% r)
ws.append(row)

for d in sorted(LAST.keys()):
    print(d, LAST[d]['last'], LAST[d]['rooms'])
    ws.append(format_last(d, LAST[d]))

wb.save("sample.xlsx")
