#!/usr/bin/env kjscmd

StdDirs.addResourceType("envelopemaker", StdDirs.kde_default("data") + "/envelopemaker");

var win = new KMainWindow(this);
var view = Factory.loadui(StdDirs.findResource("envelopemaker", "EnvelopeMakerUI.ui"), this, win);
//var view = Factory.loadui("EnvelopeMakerUI.ui", this, win);
var Print = view.child('print');
var Save = view.child('save');
var Exit = view.child('exit');

Print.connect(Print, 'clicked()', this, 'print');
Save.connect(Save, 'clicked()', this, 'save');
Exit.connect(Exit, 'clicked()', this, 'exit');

var env = new envelope();
env.init();

win.setCentralWidget(view);
win.setCaption("EnvelopeMaker");
win.show();
application.exec();

function setupEnvelope()
{
	var fontName = /(.+)[,](.+)[,](.+)[,](.+)[,](.+)[,](.+)[,](.+)[,](.+)[,](.+)[,](.+)/.exec(view.child('font').font);

	env.returnfont = fontName[1];
	env.returnpointsize = fontName[2];
	env.mailfont = fontName[1];
	env.mailpointsize = fontName[2];
	env.retAddress[0] = view.child('retAddress1').text;
	env.retAddress[1] = view.child('retAddress2').text;
	env.retAddress[2] = view.child('retAddress3').text;
	env.retAddress[3] = view.child('retAddress4').text;
	env.mailAddress[0] = view.child('mailAddress1').text;
	env.mailAddress[1] = view.child('mailAddress2').text;
	env.mailAddress[2] = view.child('mailAddress3').text;
	env.mailAddress[3] = view.child('mailAddress4').text;
	if ( view.child('barcode').checked )
	{
		if( env.getZip() == "" )
		{
			alert("You must enter a valid 9 digit Zipcode");
			return false;
		}
	}
	return true;
}

function print()
{
	if (setupEnvelope() )
	{
		var dcop = new DCOPClient();
		if( dcop.attach() )
		{
			var ps = env.header();
			ps += env.returnAddress();
			ps += env.mailingAddress();
			if( view.child('barcode').checked )
				ps += env.barcode();
			ps += env.footer();
			if ( !dcop.send("kprinterservice", "printer", "printStream(const QString&)", ps ) )
			{
				alert("There was an error talking to the KPrinterService, please check that it is running.");
			}

		}

	}
}

function save()
{
	if (setupEnvelope() )
	{
		var ps = env.header();
			ps += env.returnAddress();
			ps += env.mailingAddress();
			if( view.child('barcode').checked )
				ps += env.barcode();
			ps += env.footer();
			var fileName = StdDialog.getSaveFileName();
			if( fileName != "")
        		{
				System.writeFile(fileName, ps);
			}
	}
}

function envelope()
{
	this.init = function()
	{

		this.leftmargin = 0.30;
		this.ewidth = 9.5;
		this.eheight = 4.125;
		this.linepos = 0;
		this.normalpaper = 11;
		this.normalwidth = 8.5;

		this.feedcenter = this.normalwidth/2 - this.eheight/2
		this.topmargin =  0.30 + this.feedcenter;
		this.x0 = 0;
		this.y0 = Math.round((this.normalpaper - this.ewidth) * 72);
		this.xpos = Math.round(0.40*72*this.ewidth);
		this.ypos = Math.round(-0.40*72*this.eheight);
		this.xloc = Math.round(this.x0 + (this.topmargin * 72));
		this.yloc = Math.round(this.y0 + (this.leftmargin * 72));

		this.returnfont = "Times-Roman";
		this.returnpointsize = 12;
		this.mailfont = "Times-Roman";
		this.mailpointsize = 10;
		this.retAddress = ["Ian Reinhart Geiser","601 Coach Hill Ct","West Chester PA, 19380"];
		this.mailAddress = ["SourceXtreme, Inc","1149 Broad Run Road","Coatesville, PA 39380-9176"];
		this.zipcode = "0";
	}

	this.getZip = function()
	{
		var mailAddress = /.+,[\s]*.{2,2}[\s]+([\d]{5,5})[-]*([\d]{4,4})/.exec(this.mailAddress);
		if( mailAddress )
			return mailAddress[1] + mailAddress[2];
		else
			return "";
	}

	this.header = function()
	{
		var ps = "";
		ps += "%!\n";
		ps += "% EnvelopeMaker\n";
		// Page size
		// Comm #10 Envelope               297 x 684
		// C5 Envelope                     461 x 648
		// DL Envelope                     312 x 624
		ps += "newpath\n";
		return ps;
	}

	this.returnAddress = function()
	// Return address
	{
		var ps = this.xloc + " " + this.yloc + " translate\n";
		ps += "90 rotate";
		for ( var idx = 0; idx < this.retAddress.length; ++idx)
		{
			if( this.retAddress[idx] != "")
			{
				ps += "/" + this.returnfont + " findfont " + this.returnpointsize + " scalefont setfont\n";
				ps += "0 " + this.linepos + " moveto\n";
				ps += "(" + this.retAddress[idx] + ") show\n";
				this.linepos -= this.returnpointsize;
			}
		}
		return ps;
	}

	this.mailingAddress = function()
	// Mailing Address
	{
		var ps = "";
		for ( var idx = 0; idx < this.mailAddress.length; ++idx)
		{
			if( this.mailAddress[idx] != "")
			{
				ps += "/" + this.mailfont + " findfont " + this.mailpointsize + " scalefont setfont\n";
				ps += this.xpos + " " + this.ypos + " moveto\n";
				ps += "(" + this.mailAddress[idx] + ") show\n";
				this.ypos -= this.mailpointsize;
			}
		}
		return ps;
	}

	this.footer = function()
	{
		return "showpage\n";
	}

	this.barcode = function()
	{
		this.zipcode = this.getZip();
		if( this.zipcode.length != 9)
			return "";

		var ps = "";

		this.xpos = Math.round((this.ewidth - 3.875) * 72);
		this.ypos = Math.round((-1 * this.eheight + 0.375) * 72);

		var code = 	[ [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 1, 0, 1], [0, 0, 1, 1, 0],
				[0, 1, 0, 0, 1], [0, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0, 0, 1],
				[1, 0, 0, 1, 0],[1, 0, 1, 0, 0] ];
		var ziparray = new Array(10);

		var zipsum = 0;
		for ( var idx = 0; idx < this.zipcode.length; ++idx)
		{
			ziparray[idx] = this.zipcode.substring(idx, idx+1);
			zipsum += ziparray[idx];
		}
		var correctcode = 10 - zipsum % 10;
		if( correctcode == 10)
			correctcode = 0;
		ziparray[9] = correctcode;

		// Set our barcode dimensions to the POSTNET spec.
		// Width = 0.02"
		// Space between CL's (pitch) = 0.05"
		// Height of 1's = 0.125"
		// Height of 0's = 0.05"

		var pitch = 3.6; //points
		var linewidth = 1.44; //points
		var height = 0;

		var pos = 0;
		ps += "newpath\n";
		ps += this.xpos + " " + this.ypos + " translate\n";
		ps += pos + " 0 moveto\n";
		ps += linewidth + " setlinewidth\n";

		// Frame bar
		var height = Math.round(0.125 * 72);
		ps += "0 " + height + " rlineto\n";

		// Actual barcode
		for( var idx = 0; idx < ziparray.length; ++idx)
		{
			for (var idx2 = 0; idx2 < code[ ziparray[idx] ].length; ++idx2)
			{
				pos = Math.round(pos + pitch);
				ps += pos + " 0 moveto\n";
				var line = code[ ziparray[idx] ][idx2];
				height = Math.round((0.05 + line * 0.075) * 72);
				ps += "0 " + height + " rlineto\n";
			}
		}

		// Frame bar
		pos = Math.round(pos + pitch);
		ps += pos + " 0 moveto\n";
		height = Math.round(0.125 * 72);
		ps += "0 " + height + " rlineto\n";
		ps += "stroke\n";

        	return ps;
	}
}