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


# use mms
page_width = 210
page_height = 297
margin_left = 5
margin_top = 28.5
extra_pages = 1
with_lines = True


from copy import deepcopy
from lxml import etree
import re
import os

page_template = etree.parse('wzor.svg')
orig_text_height = float(os.popen('inkscape --query-id=textroot -H wzor.svg').read())

def mm_to_px(mm):
    return float(mm) / 25.4 * 90

def get_translate(elem):
	match = re.match("translate\((-?\d*\.?\d*),(-?\d*\.?\d*)\)", elem.get('transform'))
	return float(match.group(1)), float(match.group(2))

def set_translate(elem, x, y):
	elem.set('transform', "translate(%f,%f)" % (x, y))


root = page_template.getroot()
template_width = float(root.get('width'))
template_height = float(root.get('height'))

grid_width = int(mm_to_px(page_width) / template_width)
grid_height = int(mm_to_px(page_height) / template_height)
on_page = grid_height * grid_width

nazwiska = []
import sys
for fname in sys.argv[1:]:
	with open(fname) as f:
		nazwiska += [(n.decode('utf-8').strip('\n') + '\t\t\t').split('\t')[:4] for n in f]

nazwiska.extend(
	['', '', '', ''] for i in range((len(nazwiska) / on_page + (extra_pages + 1)) * on_page - len(nazwiska)))

root.set('width', str(mm_to_px(page_width)))
root.set('height', str(mm_to_px(page_height)))
template = root.find('{http://www.w3.org/2000/svg}g')
transform_x, transform_y = get_translate(template)
root.remove(template)

line = etree.Element('{http://www.w3.org/2000/svg}path')
line.set('style', 'stroke: #888; stroke-width: .1mm;')

x = y = page = 0
output_odd = deepcopy(page_template)
output_even = deepcopy(page_template)
for nazwisko, imie, org, funkcja in nazwiska:
	print "%s (%s)" % (nazwisko, org)
	card = deepcopy(template)
	flow = card.find('.//{http://www.w3.org/2000/svg}flowRoot')
	current_id = 'card-%d-%d' % (x, y)
	flow.set('id', current_id)
	for elem in flow.findall('.//{http://www.w3.org/2000/svg}flowPara'):
		if elem.text == u'Imię i nazwisko':
			elem.text = imie + ' ' + nazwisko
		elif elem.text == u'Organizacja':
			elem.text = org
		elif elem.text == u'Funkcja':
			elem.text = funkcja
	set_translate(card,
		transform_x + mm_to_px(margin_left) + x * template_width,
		transform_y + mm_to_px(margin_top) + y * template_height
	)
	output_even.getroot().append(card)
	# Check height
	output_even.write('tmp.svg')
	text_height = float(os.popen('inkscape --query-id=%s -H tmp.svg' % (current_id,)).read())
	tx, ty = get_translate(flow)
	set_translate(flow, tx, ty + (orig_text_height - text_height) / 2)

	odd_card = deepcopy(card)
	odd_card.set('transform', "translate(%f,%f)" % (
		transform_x + mm_to_px(page_width) - mm_to_px(margin_left) - (x + 1) * template_width,
		transform_y + mm_to_px(margin_top) + y * template_height
	))
	output_odd.getroot().append(odd_card)

	x += 1
	if x >= grid_width:
		y += 1
		x = 0
	if y >= grid_height:
		if with_lines:
			for xx in range(grid_width + 1):
				l = deepcopy(line)
				l.set('d', 'm %f,%f %f,%f' % (
						mm_to_px(margin_left) + xx * template_width,
						0,
						0,
						mm_to_px(margin_top - 1),
					))
				output_even.getroot().append(l)
				l = deepcopy(line)
				l.set('d', 'm %f,%f %f,%f' % (
						mm_to_px(margin_left) + xx * template_width,
						mm_to_px(margin_top + 1) + grid_height * template_height,
						0,
						mm_to_px(page_height) - mm_to_px(margin_top + 1) - grid_height * template_height,
					))
				output_even.getroot().append(l)
			for yy in range(grid_height + 1):
				l = deepcopy(line)
				l.set('d', 'm %f,%f %f,%f' % (
						0,
						mm_to_px(margin_top) + yy * template_height,
						mm_to_px(margin_left - 1),
						0,
					))
				output_even.getroot().append(l)
				l = deepcopy(line)
				l.set('d', 'm %f,%f %f,%f' % (
						mm_to_px(margin_left + 1) + grid_width * template_width,
						mm_to_px(margin_top) + yy * template_height,
						mm_to_px(page_width) - mm_to_px(margin_left + 1) - grid_width * template_width,
						0,
					))
				output_even.getroot().append(l)

		output_even.write('out-%02d.svg' % (2 * page))
		output_odd.write('out-%02d.svg' % (2 * page + 1))
		output_odd = deepcopy(page_template)
		output_even = deepcopy(page_template)
		page += 1
		x = y = 0

if x or y:
	output_even.write('out-%02d.svg' % (2 * page))
	output_odd.write('out-%02d.svg' % (2 * page + 1))
	page += 1

for p in range(2 * page):
	os.system('inkscape out-%02d.svg -A out-%02d.pdf' % (p, p))

os.system('pdftk %s cat output output.pdf' % (" ".join("out-%02d.pdf" % p for p in range(2*page))))
