#!/usr/bin/env python

GTEX_LETTER_VERSION = '0.30'
PRG_DIR="/opt/gnome/bin/gtex-letter-prg"
RC_FILENAME='.gtex-letterrc'


import sys
import os.path
import getopt
import ConfigParser
import string
import gettext

gettext.bindtextdomain('gtex-letter', '/usr/share/locale')
gettext.textdomain('gtex-letter')
_ = gettext.gettext

def help():
        print "usage: gtex-letter [OPTIONS] [file.tex]"
        print "       PIPE | gtex-letter [OPTIONS] [file.tex]"
	print 
        print "       -a --address     str   get address with given ID from GnomeCard-file "
	print "                                 as default address for the letter"
	print "       -s --subject     str   subject of the letter"
	print "       -o --opening     str   the letter's opening"
	print "       -f --file        str   get letter contents from file"
	print "       -c --closing     str   closing for the letter"
	print
	print "       -r --rcfile      str   use a different rc-file (.gtex-letterrc)"
	print "       -e --header      str   headerfile of the letter"
	print "          --guessformat str   the format of filename-guesses"
	print "          --guesspath   str   the path to prepend to guessed filenames"
	print "          --guilevel    str   choose the complexity of the gui used."
	print "                                 possible values are: beginner, normal"
	print "                                 and expert. While beginner-level is easy to"
	print "                                 understand, expert is very straight forward."
	print "          --nosplash          no start-screen"
	print
	print "       -n --nogui             non-interactive letter production"
	print "          --noshow            do not show the letter "
	print "                                 (only with -n/--nogui-option)" 
	print "          --quitelatex        hide latex output"
	print
	print "       -p --print             direct printing of the letter"
	print "                                 (only with -n/--nogui-option)"
	print
	print "       -h --help              print this file and exit"
	print "       -u --usage             like help"
	print "       -v --version           print version and exit"

def version():
	return "gtex-letter " + GTEX_LETTER_VERSION

FALSE=0
TRUE=-1

rc_file = RC_FILENAME
defaultaddresses = ''
closing = ''
contents= ''
contentsfile = ''
filename = ''
header = ''
opening = ''
subject = ''
guessformat = ''
guesspath = ''
quite_latex=None

nogui = FALSE
noshow = FALSE
printit = FALSE
guilevel = FALSE
splash = TRUE

opts, args = getopt.getopt(sys.argv[1:], 'a:c:e:f:hno:pr:s:uv', ['address=', 'closing=', 'file=', 'guessformat=', 'guesspath=', 'guilevel=', 'header=', 'help', 'nogui', 'noshow', 'nosplash', 'opening=', 'print', 'quitelatex', 'rcfile=', 'subject=', 'usage', 'version'])
for opt in opts:
	option = opt[0]
	value = opt[1]
	if option =='-a' or option =='--address':
		defaultaddresses = value
	elif option =='-c' or option =='--closing':
		closing = value
	elif option =='-f' or option =='--file':
		contentsfile = value
		if not os.path.isfile(contentsfile):
			print _('Error: Provided file not found.')
			sys.exit()
		file = open(contentsfile, 'r')
		contents= file.read()
		file.close()
	elif option =='--guilevel':
		guilevel = value
	elif option =='-e' or option =='--header':
		header = value
	elif option =='--guessformat':
		guessformat = value
	elif option =='--guesspath':
		guesspath = value
	elif option =='-h' or option =='--help':
		help()
		sys.exit()
	elif option =='-n' or option =='--nogui':
		nogui = TRUE
	elif option =='--noshow':
		noshow = TRUE
	elif option =='--nosplash':
		splash = FALSE
	elif option =='-o' or option =='--opening':
		opening = value
	elif option =='-p' or option =='--print':
		printit = TRUE
	elif option =='--quitelatex':
		quite_latex = TRUE
	elif option =='-r' or option =='--rcfile':
		rc_file = value
		if not os.path.isfile(rc_file):
			print _('Error: Provided rc-file not found.')
			sys.exit()
	elif option =='-s' or option =='--subject':
		subject = value
	elif option =='-u' or option =='--usage':
		help()
		sys.exit()
	elif option =='-v' or option =='--version':
		print version()
		sys.exit()

if (noshow or printit) and not nogui:
	print _("Error: You may not set the noshow or the print option without setting nogui.")
	sys.exit()




# fetch the STDIN if it is set.
if not sys.stdin.isatty(): # redirected from file or pipe
	if not contents:
		contents = sys.stdin.read()
	elif contents and not defaultaddress:
		defaultaddress = sys.stdin.read()[:-1]  # remove CR-char
	else:
		print _("Error: I do not know what to do with STDIN (pipe). You set both, -f/--file and -a/--address, in the options, so there is no place to put the pipe.")
		sys.exit()

if args:
	filename = args[0]
	






sys.argv=['']  # i get an error from module gui, if there are options left in sys.argv

import utils, addressbook_vcard, gui    # if i put this before the opts-stuff, 
import mk_letter, config		# the options are unknown...
import error




class gtex_letter:
	def __init__ (self, rc, \
			filename = '',\
			addresskeys = '',\
			closing = '',\
			contents = '',\
			header = '',\
			opening = '',\
			subject = ''):
 
		self.init_address(addresskeys, rc)
		
		self.init_header(header, rc)

		self.subject = subject
		self.opening = opening
		self.contents = contents
		self.closing = closing

		self.filename = filename

		if not self.filename:
			file = utils.guess_filename(self, rc)
			if file:
				self.filename = file

		self.path = utils.get_path_from_file(self.filename)
		self.letter_written = FALSE
			

	def init_address(self, addresskeys, rc):
		self.address = ''

		self.addresscards = []

		if addresskeys:
			list = []
			while 1:
				hit = string.find(addresskeys, ',')
				if hit == -1:
					list.append(string.strip(addresskeys))
					addresskeys=''
					break
				list.append(string.strip(addresskeys[:hit]))
				addresskeys = addresskeys[hit+1:]
			ab = addressbook_vcard.addressbook(rc.addressbooks)
			ab.read_file()
			for name in list:
				try: 
					card = ab.get_card(name)
					if card:
						self.addresscards.append(card)
					else:
						raise error.AddressCardNotFound, name
				except error.AddressCardNotFound, cardname:
					print _("The addresscard '%s' could not be found.") % cardname
					
			for card in self.addresscards:
				if self.address:
					self.address = self.address + '\n'
				self.address = self.address + utils.mk_adr(card, \
							rc.addressformats, rc.mycountry)
				
			if self.address:
				self.address_slashes = utils.add_slashes(self.address)
			
		if not self.address:
			self.address_slashes = ''
	
	def init_header(self, header, rc):
		self.header = ''
		if header:
			self.header = header  
		else:
			if rc.headerdefaults:
				self.header = rc.headerdefaults[0]
		try:
			if self.header:
				if self.header[-4:] <> '.tex': 
					self.header = self.header + '.tex' 
				self.header = utils.get_path(self.header, rc.prg_dir)
				if self.header:
					if not os.path.split(self.header)[0]: # if it is still local
						self.header = os.path.join(os.getcwd(), \
								self.header)
				else:
					raise IOError, header
		except IOError, file:
			print _("Submitted headerfile '%s' not found") % file
			

	
def main ():
	rc = config.gtex_letter_config(rc_file, nogui=nogui, \
			noshow=noshow, splash=splash, \
			printit=printit, guilevel=guilevel, \
			guessformat=guessformat, guesspath=guesspath, quite_latex=quite_latex, prg_dir=PRG_DIR )
			
	letter = gtex_letter(rc, filename, defaultaddresses, \
				closing, contents, \
				header, opening, subject)
	if rc.nogui:
		letter.letter_written = not mk_letter.write_file(letter, rc)
		if not letter.letter_written: 
			print _("Aborting.")
			sys.exit()
		mk_letter.tex_latex(letter, rc)
		if not rc.noshow:
			mk_letter.tex_xdvi(letter, rc)
		if printit:
			mk_letter.tex_print(letter, rc)
		mk_letter.rm_latex_files(letter)
	else:
		gp = gui.GUI (rc, letter)
		gp.mainloop ()

if __name__ == '__main__':
	main ()