from server import *

@app.route('/internal/timetable')
@register_navbar('Drehplan', icon='calendar')
@mod_required
def timetable():
	if 'kw' not in request.args:
		kw=0
	else:
		kw=int(request.args['kw'])
	try:
		start = date.today() - timedelta(days=date.today().weekday() -7*kw)
	except:
		start = date.today() - timedelta(days=date.today().weekday())
	days = [{'date': start, 'lectures': [], 'atonce':0, 'index': 0 }]
	earlieststart=time(23,59)
	latestend=time(0,0)
	for i in range(1,7):
		days.append({'date': days[i-1]['date'] + timedelta(days=1), 'atonce':0, 'index': i, 'lectures':[] })
	for i in days:
		# date and times are burning in sqlite
		s = datetime.combine(i['date'],time(0,0))
		e = datetime.combine(i['date'],time(23,59))
		i['lectures'] = []
		for l in query ('''
					SELECT lectures.*, courses.short, "course" AS sep, courses.*
					FROM lectures 
					JOIN courses ON (lectures.course_id = courses.id) 
					WHERE time < ? and time > ?
					ORDER BY time ASC''', i['date']+timedelta(weeks=2), i['date']-timedelta(weeks=2)):
			# we can not use the where clause of sql to match against the time, because sqlite and mysql use a different syntax -.-
			# we still use it to only get the lectures for a 3 week periode
			if not l['time']:
				l['time'] = datetime.fromtimestamp(0)
			if ((l['time'] < e) and (l['time'] > s)) or ((l['time'] + timedelta(minutes=l['duration']) < e) and (l['time'] + timedelta(minutes=l['duration'])> s)):
				i['lectures'].append(l)
				oldtime = l['time']
				l['time'] = max(s,l['time'])
				l['duration'] = ( min(e,oldtime + timedelta(minutes=l['duration'])) - l['time'] ).total_seconds()/60
		# sweepline to find out how many lectures overlap
		maxcol=0;
		curcol=0;
		freecol=[];
		for l in i['lectures']:
			# who the hell inserts lectures with zero length?!?!?
			l['time_end'] = l['time']+timedelta(minutes=max(l['duration'],1))
		# create sweepline input array
		sweeplinetupels =  [(l['time'],True,l) for l in i['lectures']]
		sweeplinetupels += [(l['time_end'],False,l) for l in i['lectures']]
		tmp = []
		for x in sweeplinetupels:
			unique = True
			for y in tmp:
				if x[0] == y[0] and x[1] == y[1] and x[2]['short'] == y[2]['short']:
					unique = False
			if unique:
				tmp.append(x)

		sweeplinetupels = sorted(tmp, key=lambda t:(t[0],t[1]))
		for l in sweeplinetupels:
			if l[1]:
				curcol += 1
				if curcol > maxcol:
					maxcol = curcol
				if len(freecol) == 0:
					freecol.append(maxcol)
				l[2]['timetable_col'] = freecol.pop()
				if earlieststart > l[0].time():
					earlieststart = l[0].time()
			else:
				curcol -= 1
				freecol.append(l[2]['timetable_col'])
				if latestend < l[0].time():
					latestend = l[0].time()
		i['maxcol'] = max(maxcol,1)
	times=[]
	s = min(earlieststart,time(8,0))
	e = max(latestend,time(19,0))
	for i in range(s.hour*4,min(int((60*e.hour/15)/4)*4+5,24*4)):
		t = i*15
		times.append(time(int(t/60),t%60))
	return render_template('timetable.html',days=days,times=times,kw=kw)