# Copyright (C) 2001 Tobias Peters <t-peters@berlios.de>
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA  02111-1307, USA.

class Idl_Constant
  attr_reader :interface
  attr_reader :ptype
  attr_reader :name
  attr_reader :value
  attr_reader :idl_module

  def initialize (idl_module, # a reference to the module
		  interface,  # a refereence to the containing interface
		  idl_string) # the text line containing the IDL declaration
    @interface = interface
    @idl_module = idl_module

    # extract data type, identifier and constant value from the IDL string
    match =
      /\s*const\s+(.*[^\s])\s+([^\s]+)\s*=\s*([^\s;]+);/.match(idl_string)
    @ptype     = match[1]
    @name      = match[2]
    @value     = match[3]

    description = "constant #{@ptype} "
    if (interface != nil) 
      description << interface.name()
    end
    puts("#{description}::#{@name} = #{@value}") if ($verbose)

    if (name =~ /_NODE$/)
      @idl_module.add_node_constant(self)
    end
  end

  # if this is a node type constant, this method returns a reference to the
  # Idl_Interface object associated with this node type
  def get_matching_interface()
    interface = nil
    if (@name =~ /_NODE$/)
      mangled_name = @name.sub(/_NODE$/, "").gsub(/_/, "").downcase()
      @idl_module.interfaces().each {|i|
	if ((i.name().downcase() == mangled_name) ||
	    ((i.name() == "Attr") && (mangled_name == "attribute")))
	  interface = i
	end
      }
    end
    interface
  end


  ####################
  def create_ruby_code()
    constant_holder =
      @interface ? rbdom_class_name(@interface) : @idl_module.get_c_value_name
    init_func_code =
      ("  rb_define_const(#{constant_holder}, \"#{@name}\", \n" +
       "                  INT2NUM(#{@value}));              \n")
    @idl_module.add_ruby_code("init_func", init_func_code)
  end


  ###################
  def create_cpp_code(gdome_cpp_hh)
    # constants are enums now
    gdome_cpp_hh << "  #{@name} = #{@value},\n"
  end
end
