#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Sebastian Pipping <sebastian@pipping.org>
# Licensed under GPL v3 or later

from __future__ import print_function
import sys
import simplejson as json
import tempfile
import os
import subprocess
import shutil

sys.path.insert(0, '../client-barcode')  # TODO
from freitagslib.network import _request
from freitagslib.item import Item


_NAME_BLACKLIST = ('foo', )
_BASENAME = 'preisliste'


def write_utf8(f, text):
	f.write(unicode(text).encode('utf8'))

def escape(text):
	return text.replace('&', '\\&')


def german(phormat, value):
	return (phormat % value).replace('.', '{,}')


if __name__ == '__main__':
	if len(sys.argv) != 2:
		print('USAGE:\n  ./%s OUTPUT.pdf' % os.path.basename(sys.argv[0]))
		sys.exit(1)
	output_filename = sys.argv[1]

	content = _request('buyable/item/', None, method='GET')
	doc = json.loads(content)
	items = [Item(e) for e in doc]

	tempdir = tempfile.mkdtemp()
	preisliste_tex = os.path.join(tempdir, _BASENAME + '.tex')
	preisliste_pdf = os.path.join(tempdir, _BASENAME + '.pdf')

	f = open(preisliste_tex, 'w')

	f.write(r"""
\documentclass[a4paper,10pt]{scrartcl}

\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage{fullpage}
\usepackage{booktabs}
\usepackage{eurosym}

% Reduce vertical offset
\addtolength{\textheight}{\voffset}
\setlength{\voffset}{0cm}
\setlength{\voffset}{-1cm}
\addtolength{\textheight}{1cm}

% No footskip
\addtolength{\textheight}{\footskip}
\setlength{\footskip}{0cm}

% No footskip
\addtolength{\textheight}{\footskip}
\setlength{\footskip}{0cm}

% No page number
\pagestyle{empty}

\begin{document}
\begin{flushright}Stand \today\end{flushright}
\vspace*{-4.6ex}
%
\begin{tabular}{l@{\quad}rr}
\toprule
Artikel & \multicolumn{1}{c}{Preis} & \multicolumn{1}{c}{Pfand} \\
\midrule
""")

	first = True
	for i in sorted(items, cmp=lambda x,y: cmp(x.name.lower(), y.name.lower())):
		if i.name in _NAME_BLACKLIST:
			continue

		latex_name = escape(i.name)
		latex_name = '\\textbf{%s}%s' % (latex_name[0], latex_name[1:])
		latex_price = german('\\textbf{%.2f} \\euro', i.price)
		latex_deposit = '~' if i.deposit == 0 else german('+ %.2f \\euro', i.deposit)

		write_utf8(f, '%s%s & %s & %s \\\\\n' % (
				'' if first else '\\midrule\n',
				latex_name, latex_price, latex_deposit))
		first = False

	f.write(r"""\bottomrule
\end{tabular}
\end{document}
""")
	f.close()

	ret = subprocess.call(['pdflatex', _BASENAME + '.tex'], cwd=tempdir)
	if ret != 0:
		print("Call to LaTeX failed with code %d." % ret)
		sys.exit(ret)

	print('Moving output to "%s"...' % output_filename)
	shutil.move(preisliste_pdf, output_filename)

	print('Wiping directory "%s"...' % tempdir)
	shutil.rmtree(tempdir)
