module LogMixin
  attr_accessor :logging
  def LogMixin.included(base)
    base.after_create :create_log
    base.after_update :update_log
    base.after_destroy :destroy_log
    base.class_eval do
      class << self
        def add_callbacks_for_logging
          reflections.each_pair do |reflection_name, reflection|
            if reflection.macro == :has_and_belongs_to_many
              add_association_callbacks(reflection_name, {:after_add=>:add_log_for_has_and_belongs_to_many, :after_remove=>:remove_log_for_has_and_belongs_to_many})
            elsif reflection.macro == :has_many
              add_association_callbacks(reflection_name, {:after_add=>:add_log_for_has_many, :after_remove=>:remove_log_for_has_many})
            end
          end
        end

      end
    end
    base.add_callbacks_for_logging
  end


  def after_initialize
    self.logging = Log.new({:klass=>self.class.to_s})
  end

  def add_log_for_has_and_belongs_to_many object
    @logging.attributes = {:aktion=>@logging.aktion||l(:log_add_for_has_many_default), :changes=>''}
    save_log
  end

  def remove_log_for_has_and_belongs_to_many object
    @logging.attributes = {:aktion=>@logging.aktion||l(:log_remove_for_has_many_default), :changes=>''}
    save_log
  end

  def add_log_for_has_many object
    @logging.attributes = {:aktion=>@logging.aktion||l(:log_add_for_has_many_default), :changes=>''}
    save_log
  end

  def remove_log_for_has_many object
    @logging.attributes = {:aktion=>@logging.aktion||l(:log_remove_for_has_many_default), :changes=>''}
    save_log
  end

  def create_log
    @logging.attributes = {:aktion=>@logging.aktion||l(:log_create_default), :changes=>''}
    save_log
  end

  def update_log
    @logging.attributes = {:aktion=>@logging.aktion||l(:log_update_default), :changes=>''}
    save_log
  end

  def destroy_log
    @logging.attributes = {:aktion=>@logging.aktion||l(:log_destroy_default), :changes=>''}
    save_log
  end
private
  def save_log
    @logging.attributes = {:object_id=>@logging.object_id||self.id, :person_id=>self.person_id}
    @logging.save
  end

end