# -*-python-*-
# vim: ts=4

import handlerbase

class IDLHandler(handlerbase.HandlerBase):
	def __init__(self):
		pass

	def extensions(self):
		return ['.stub', '.skel']

	def source(self, program, base, ext):
		sourcename = base + "_" + ext[1:]

		rulef = program.amfile.rulef
		
		sourcedir = ''
		if program.amfile.in_srcdir( base + ".h" ):
			sourcedir = rulef.source
		else:
			value = program.amfile.value_of(base + "_DIR")
			if value:
				sourcedir = re.sub('^\$\(srcdir\)', rulef.source, value)
				if not sourcedir[-1] == '/':
					sourcedir = sourcedir + '/'
			else:
				sourcedir = rulef.build

		if program.amfile.value_of(base + "_DCOPIDLNG"):
			dcopidl = "KDECONFIG=\"$(KDECONFIG)\" $(DCOPIDLNG)"
		else:
			dcopidl = "$(DCOPIDL)"
					
		rulef.insertTarget(rulef.build + base + ".kidl",
				   [sourcedir + base + ".h",
				    "$(DCOP_DEPENDENCIES)"],
				   ["@echo 'creating " + rulef.build + base + ".kidl'",
					"@adir=`cd %s && pwd` ;\\" % sourcedir,
					dcopidl + " $$adir/" + base + ".h > " + rulef.build + base + ".kidl "
				    "|| ( rm -f " + rulef.build + base + ".kidl ;"
				    " false )"])
		
		if ext == '.skel':
			rulef.insertTarget(rulef.build + sourcename + ".cpp", [rulef.build + base + ".kidl",
									       "$(DCOPIDL2CPP)"],
					   ["@echo 'creating " + rulef.build + sourcename + ".cpp'",
						"@$(DCOPIDL2CPP) --c++-suffix cpp "
					    "--no-stub %s" % rulef.build + base + ".kidl"])
		else: #elif ext == '.stub':
			rulef.insertTarget(rulef.build + sourcename + ".cpp",
					   rulef.build + sourcename + ".h")
			rulef.insertTarget(rulef.build + sourcename + ".h", [rulef.build + base + ".kidl",
									     "$(DCOPIDL2CPP)"],
					   ["@echo 'creating " + rulef.build + sourcename + ".h'",
						"@$(DCOPIDL2CPP) --c++-suffix cpp "
					    "--no-skel %s" % rulef.build + base + ".kidl"])
		#else:
		#	rulef.insertTarget(rulef.build + sourcename + ".cpp",
		#			   rulef.build + sourcename + ".h")
		#	program.amfile.insertTarget(rulef.build + sourcename + ".h", [rulef.build + base + ".kidl",
		#								   "$(DCOPIDL2CPP)"],
		#				 ["$(DCOPIDL2CPP) --c++-suffix cpp "
		#				  "--no-stub --no-skel %s" % rulef.build + base + ".kidl"])
			
		program.handle_source(sourcename, ".cpp")

		if ext != '.skel':
			program.amfile.add_define(program.canon_name + "_COMPILE_FIRST",
									  sourcename + ".h")
			
		program.cleanfiles.extend([sourcename + ".cpp",
								   sourcename + ".h",
								   base + ".kidl"])

register_handler(IDLHandler())
