class NodeEntityAbstract < ActiveRecord::Base

  self.abstract_class = true

  before_save :save_node
  after_destroy :destroy_node

  class << self
    alias :_find :find
    def find(*args)
      nodes = Node.send("find_#{table_name}",*args)
      case nodes
      when Node
        return nodes.entity
      when Array
        return nodes.collect{|n| n.entity}
      else
        return nodes
      end
    end
  end


  def initialize(attrs=nil)
    attrs_node = Hash.new
    if attrs
      Node.column_names{|cname|
        if ( v=attrs.delete(cname) )
          attrs_node[cname] = v
        end
      }
    end
    super(attrs)
    node = Node.new(attrs_node)
    node.node_type = Node.const_get(self.class.table_name.singularize.upcase)
    self.node = node
    node.entity = self
  end

  def node
    return @node if @node
    if node_id
      @node = Node.find(node_id, :user => :all)
      return @node
    end
    return nil
  end

  (%w(owner
     keyword_attributes spatial_and_time_attributes
     draw_parameters
     references referenced_by
     fname
     ) +
    Node.column_names
   ).each do |name|
    next if name=="id" || name=="node_type"
    if name =~ /^(.*)_id/
      name = $1
    end
    eval <<-"EOF"
      def #{name}
        node && node.#{name}
      end
      def #{name}=(val)
        node && node.#{name} = val
      end
    EOF
  end


  protected
  def save_node
    if node.save
      self.node_id = node.id
      return true
    else
      node.errors.each{|k,v| errors.add(k,v) }
      return false
    end
  end

  def destroy_node
    node.destroy
  end

=begin
  def method_missing(method_id, *args)
    begin
      super(method_id, *args)
    rescue NoMethodError
      error = $!
      begin
        node.send(method_id, *args)
      rescue NoMethodError
        raise error
      end
    end
  end
=end

  def node=(node)
    @node = node
  end


end
