
gen::add_generator Processing.org gen_processing::generate

namespace eval gen_processing {

proc highlight { tokens } {

	return [ gen_java::highlight $tokens ]
}

proc make_callbacks { } {
	set cbks [ gen_java::make_callbacks ]
	set cbks [ dict replace $cbks signature gen_processing::extract_signature ]
	set cbks [ dict replace $cbks body gen_processing::generate_body ]
	return $cbks
}



proc generate_body { gdb diagram_id start_item node_list sorted incoming } {
	set callbacks [ make_callbacks ]
	return [ cbody::generate_body $gdb $diagram_id $start_item $node_list \
		$sorted $incoming $callbacks ]
}


proc generate { db gdb filename } {
	set callbacks [ make_callbacks ]

	gen::fix_graph $gdb $callbacks 1
	unpack [ gen::scan_file_description $db { header footer } ] header footer

	set use_nogoto 1
	set functions [ gen::generate_functions $db $gdb $callbacks $use_nogoto ]

	if { [ graph::errors_occured ] } { return }


	set hfile [ replace_extension $filename "pde" ]
	set f [ open_output_file $hfile ]
	catch {
		p.print_to_file $f $functions $header $footer
	} error_message

	catch { close $f }
	if { $error_message != "" } {
		error $error_message
	}
}

proc build_declaration { name signature } {
	unpack $signature type access parameters returns
	set params {}
	foreach par $parameters {
		lappend params [ lindex $par 0 ]
	}
	set param_text [ join $params ", " ]
	if { $type == "procedure" } {
		return "$returns $name\($param_text\) \{"
	} else {
		return "$name\($param_text\) \{"
	}	
}

proc p.print_to_file { fhandle functions header footer } {
	set version [ version_string ]
	puts $fhandle \
	    "// Autogenerated with DRAKON Editor $version"

	puts $fhandle "import java.util.Iterator;"

	if { $header != "" } {
		puts $fhandle $header
	}


	foreach function $functions {
		unpack $function diagram_id name signature body
		set type [ lindex $signature 0 ]
		if { $type != "comment" } {
			puts $fhandle ""
			set declaration [ build_declaration $name $signature ]
			puts $fhandle $declaration
			set lines [ gen::indent $body 1 ]
			puts $fhandle $lines
			puts $fhandle "\}"
		}
	}
	puts $fhandle ""
	puts $fhandle $footer
}



proc extract_signature { text name } {
	set lines [ gen::separate_from_comments $text ]
	set first_line [ lindex $lines 0 ]
	set first [ lindex $first_line 0 ]
	if { $first == "#comment" } {
		return [ list {} [ gen::create_signature "comment" {} {} {} ]]
	}
	
	set type "procedure"
	if { $first == "ctr" } {
		set type "ctr"
		set lines [ lrange $lines 1 end ]
	}
	
	set last [ lindex $lines end ]
	set returns_expr [ lindex $last 0 ]
	if { [ string match "returns *" $returns_expr ] } {
		set returns [ lindex $returns_expr 1 ]
		set parameters [ lrange $lines 0 end-1 ]
	} else {
		set returns "void"
		set parameters $lines
	}

	return [ list {} [ gen::create_signature $type public $parameters $returns ] ]
}

}

