#!/usr/bin/env python

# Scribus script > 1.3 compatible
# HEAVILY based on IDgen-NG from http://thelirium.net/scribus
# Giorgos Logiotatidis (seadog@sealabs.net)
# Under the GPL Licence

from scribus import *
import os

WIDTH=209.903 # page width
HEIGHT=297.039 # page height
MARGINS=(3.175, 3.175, 3.175, 3.175) # margins (left, right, top, bottom) ?
nol=0 # number of lines in input file 
CARDWIDTH=65 # card width
CARDHEIGHT=90 # card height
DIR = "."

def create_image(filename, roffset, coffset, w, h, marginl, margint):
	n=createImage(marginl+(roffset-1)*w,margint+(coffset-1)*h, CARDWIDTH, CARDHEIGHT)
	loadImage(filename,n)
	scaleImage(CARDWIDTH, CARDHEIGHT, n)
	setScaleImageToFrame(True, False, n)

	return True

def get_multipl(total, width, marginl=0, marginr=0):
	e=divmod(total-(marginl+marginr), width)
	return e[0]
	
colstotal=get_multipl(WIDTH, CARDWIDTH, MARGINS[0])
rowstotal=get_multipl(HEIGHT, CARDHEIGHT, MARGINS[2])
progressTotal(nol)
messagebarText("Processing "+str(nol)+" elements")

if haveDoc!=True:
	t=newDoc((WIDTH,HEIGHT), MARGINS, PORTRAIT, 1, UNIT_MILLIMETERS, FACINGPAGES, FIRSTPAGERIGHT)
	cr=1
	cc=1
	total=0
	rejected=0
	
	DIR = fileDialog("Open file with data", '*.jpg', isdir=True)

	for j in os.listdir(DIR):
		create_image(DIR+j, cr, cc, CARDWIDTH, CARDHEIGHT, MARGINS[0], MARGINS[2])
	
		if cr==colstotal and cc==rowstotal:
			newPage(-1)
			gotoPage(pageCount())
			cr=1
			cc=1
		else:
			if cr==colstotal:
				cr=1
				cc=cc+1
			else:
				cr=cr+1
		progressSet(total)
	progressSet(nol)

	messagebarText("Processed "+str(total)+" items. "+str(rejected)+" rejected.")


