#!/usr/bin/env python3
from util import ping_job, getcurjobid, getjobdata, buildpath, job_failed
from PIL import Image, ImageFont, ImageDraw
import traceback
import sys
import json
import os

def centerText(img, draw, fnt, top, msg, color='white'):
	iw, ih = img.width, img.height
	tw, th = draw.textsize(msg, font=fnt)
	draw.text(((iw-tw)/2, top), msg, font=fnt, fill=color)

def main():
	if not len(sys.argv) == 5:
		exit(1)
	data = getjobdata()
	outputfile = buildpath(os.environ.get('WORKER_RAW'), data['path']);
	data = data['metadata']
	with Image.new("RGB",(1920,1080),"black") as img:
		fontpath = 'assets/LiberationSans-Regular.ttf'
		draw = ImageDraw.Draw(img)
		fnt = ImageFont.truetype(fontpath, 92)
		centerText(img, draw, fnt, 270, data.get('album', ''))
		fnt = ImageFont.truetype(fontpath, 69)
		centerText(img, draw, fnt, 500, data.get('artist', ''))
		fnt = ImageFont.truetype(fontpath, 72)
		centerText(img, draw, fnt, 710, '{} vom {}'.format(data.get('title', ''), data.get('date', '').replace('/', '.')))
		fnt = ImageFont.truetype(fontpath, 36)
		centerText(img, draw, fnt, 910, 'Video erstellt von der Video AG der Fachschaft I/1')
		linkblue = (81, 122, 231)
		fnt = ImageFont.truetype(fontpath, 38)
		centerText(img, draw, fnt, 950, 'https://video.rwth-aachen.de/', color=linkblue)
		centerText(img, draw, fnt, 990, 'video@fsmpi.rwth-aachen.de', color=linkblue)
		with Image.open('assets/lgog_embed2.png') as logo:
			img.paste(logo,(1722, 924))
		img.save(outputfile, "PNG")
	ping_job('finished')
	exit(0)

if __name__ == '__main__':
	try:
		main()
	except Exception as e:
		try:
			job_failed(str(e))
		except:
			traceback.print_exc()
			exit(3)