from server import *

@job_handler('probe', 'probe-raw')
def import_xmp_chapters(jobid, jobtype, data, state, status):
	if 'lecture_id' not in data and data.get('import-chapters', False):
		return
	times = set()
	# Only add new chapters, deleted chapters are taken into account here
	for chapter in query('SELECT * FROM chapters WHERE lecture_id = ?', data['lecture_id']):
		for offset in range(5):
			times.add(chapter['time']-offset)
			times.add(chapter['time']+offset)
	for chapter in status.get('xmp_chapters', []):
		if int(chapter['time']) in times:
			continue
		modify('INSERT INTO chapters (lecture_id, time, text, visible, time_created, time_updated) VALUES (?, ?, ?, 0, ?, ?)',
				data['lecture_id'], int(chapter['time']), chapter['text'],
				datetime.now(), datetime.now())

@job_handler('probe', 'remux', 'transcode')
def update_video_metadata(jobid, jobtype, data, state, status):
	if 'video_id' not in data:
		return
	if jobtype not in ['remux', 'transcode']:
		video = query('SELECT * FROM videos WHERE id = ?', data['video_id'])[0]
		if video['hash'] and video['hash'] != status['hash']:
			print('Hash mismatch for video', data['video_id'])
			return
	modify('UPDATE videos_data SET hash = ?, file_size = ? WHERE id = ?',
			status['hash'], status['filesize'], data['video_id'])

def schedule_remux(lectureid):
	lecture = query('SELECT * FROM lectures WHERE id = ?', lectureid)[0]
	course = query('SELECT * FROM courses WHERE id = ?', lecture['course_id'])[0]
	chapters = query('SELECT text, time FROM chapters WHERE lecture_id = ?', lectureid)
	videos = query('SELECT videos.*, sources.path AS srcpath, sources.hash AS srchash FROM videos JOIN sources ON videos.source = sources.id WHERE videos.lecture_id = ?', lectureid)
	metadata = {'title': lecture['title'], 'album': course['title'],
		'description': lecture['comment'],
		'date': lecture['time'].strftime('%m/%d/%Y'),
		'artist': lecture['speaker'] if lecture['speaker'] else course['organizer']}
	for video in videos:
		if not video['source']:
			continue
		data = {'video_id': video['id'], 'path': video['path'],
			'srcpath': video['srcpath'], 'srchash': video['srchash'],
			'chapters': chapters, 'metadata': metadata}
		schedule_job('remux', data)

@edit_handler('chapters')
def chapter_changed(table, column, value, id):
	print('chapter_changed')
	chapters = query('SELECT * FROM chapters WHERE id = ?', id)
	if not chapters:
		return
	chapter = chapters[0]
	if column in ['visible', 'deleted'] or (chapter['visible'] and not chapter['deleted']):
		schedule_remux(chapter['lecture_id'])

@edit_handler('courses')
def course_changed(table, column, value, id):
	if column not in ['title', 'organizer']:
		return
	lectures = query('SELECT * FROM lectures WHERE course_id = ?', id)
	for lecture in lectures:
		schedule_remux(lecture['id'])

@edit_handler('lectures')
def lecture_changed(table, column, value, id):
	if column in ['title', 'comment', 'time', 'speaker']:
		schedule_remux(id)