#
#  COBJ - utilities for creating/destroying (SWIG) object instances
#
# This utility provide two commands 
#   OBJ::NEW and OBJ::DELETE
# for creating/destroying object instances provided by the SWIG compiler.
#
# OBJ::NEW allows to create new objects without requiring to specify a unique name
# OBJ::DELETE destroys both the 'command-object' AND invokes the destructor of 
#	underlying C/C++ object.
#
#    set myObj [COBJ::NEW  ?_ns_::?_class_  ?_params_? ]
#      $myObj _method1_ _args_
#    COBJ::DELETE $myObj
#
# Aug-2015 - A.Buratti

 
namespace eval COBJ {
if 0 {
	array set OBJDB {}
	
	 # parameters:
	 #   ns_class  is the class (fully qualified with namespace)
	 #   args      are the parameters for the class constructor
	 # return:
	 #   the name of the new object (i.e. a new tcl-command)
	proc NEW { ns_class args } {
		variable OBJDB
		set ns [namespace qualifiers $ns_class]
		set class [namespace tail $ns_class]
		 # create the object and store it in OBJDB (as helper for DELETing ..)
		set objCmd [${ns}::new_${class} {*}$args]
		set OBJDB($objCmd) [list $ns $class]
		return $objCmd
	}
	
	 # destroys the object $objCmd (i.e. the tcl-command $obj) and invokes the
	 #  destructor of the underlying c/cèè object.
	 #
	 # Note that if $objCmd has not been created with NEW, or if $objCmd 
	 #  has been previosly deleted, nothing happens ...
	proc DELETE {objCmd} {
		variable OBJDB
		if { ! [info exists OBJDB($objCmd)] } return
		lassign $OBJDB($objCmd) ns class
		unset OBJDB($objCmd)
	
		rename $objCmd {} ;# same as $objCmd -delete
		${ns}::delete_${class} $objCmd ;# call the c/c++ destructor
	}
}

	proc NEW { ns_class args } {
		set ns [namespace qualifiers $ns_class]
		set class [namespace tail $ns_class]
		 # create the object and store it in OBJDB (as helper for DELETing ..)
		set objCmd [${ns}::new_${class} {*}$args]
		$objCmd -acquire
		return $objCmd
	}
	proc DELETE {objCmd} {
		 # if [objCmd cget -thisown] is true, the following command also calls
		 #  the C/C++ destructor.
		$objCmd -delete
	}
	
}
