#!/usr/bin/python

from os import system
import fileinput
import sys
import io
import glob
import os

def replace_text(outtext,balise,text):
	return outtext.replace(balise, text, 1)

def generate_nom(nom):
	return nom

def generate_descr(descr):
	return descr

def generate_fulldescr(fulldesc):
	textlist = fulldesc.split("\n")
	outfulldescr = ""
	for line in textlist:
		outfulldescr = outfulldescr+"<flowPara>"+line+"</flowPara>"
	return outfulldescr

def generate_num(num):
	return num
	
def replace(intext, substitutions):
	outtext = intext
	for patern, text in substitutions:
		outtext = replace_text(outtext, patern, text)
	return outtext

def substitutions_from_descrfile(descfile):
	#read description file
	#dfile = io.open(descfile, "r",encoding='iso-8859-15')
	dfile = io.open(descfile, "r",encoding='utf-8')
	desctext = dfile.read()
	dfile.close()

	#split the description file
	desclist = desctext.split("-----\n")
	out = []
	out.append( ["##NOM##", generate_nom(desclist[0]).replace('\n','')])
	out.append( ["##DESC##", generate_fulldescr(desclist[1]).replace('\n','')])
	out.append( ["##NUM##", generate_num(desclist[2]).replace('\n','')])
	return out

def generate_file(infile, outfile, sub):

	#read svg template
	ifile = io.open(infile, "r",encoding='utf8')
	intext = ifile.read()
	ifile.close()

	outtext = replace(intext, sub)

	#write out file
	outfile = io.open(outfile, "w")
	outfile.write(outtext)
	outfile.close()


#generate_file(str(sys.argv[1]),str(sys.argv[2]),str(sys.argv[3]))
template = str(sys.argv[1])
tempdir = str(sys.argv[2])
descdir = str(sys.argv[3])

listes = glob.glob(descdir+"list_*.txt")
print(listes)
if listes:
	for listfile in listes:
		filename = os.path.splitext(os.path.basename(listfile))[0]
		print("nouvelle liste: "+filename)
		with open(listfile) as f:
			sub = []
			for line in f:
				sub=sub+substitutions_from_descrfile(descdir+""+line.rstrip('\n')+".txt")
				sub.append(["##IMG##", descdir+"/"+line.rstrip('\n')+".png"])

		generate_file(template, tempdir+"_"+filename+".svg", sub)
else:
	print(descdir+"*.txt")
	descfiles = glob.glob(descdir+"*.txt")
	idtmp = 0
	for descfile in descfiles:
		filename = os.path.splitext(os.path.basename(descfile))[0]
		imgfile = os.path.splitext(descfile)[0]+".png"
		print("descfile: "+descfile)
		print("imgfile: "+imgfile)
		#generate substitution list
		sub = substitutions_from_descrfile(descfile)
		sub.append(["##IMG##", imgfile])

		generate_file(template, tempdir+"_"+filename+".svg", sub)
		idtmp = idtmp +1

