module EasyPatch
  module ActsAsEasyJournalized

    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods

      def acts_as_easy_journalized(options = {})
        return if self.included_modules.include?(EasyPatch::ActsAsEasyJournalized::EasyJournalizedMethods)

        default_options = {
          :non_journalized_columns => %w(id created_on updated_on updated_at created_at lft rgt lock_version),
          :important_columns => [],
          :format_detail_date_columns => [],
          :format_detail_time_columns => [],
          :format_detail_reflection_columns => [],
          :format_detail_boolean_columns => [],
          :format_detail_hours_columns => []
        }

        cattr_accessor :journalized_options
        self.journalized_options = default_options.dup

        options.each do |k,v|
          self.journalized_options[k] = Array(self.journalized_options[k]) | v
        end

        send :include, EasyPatch::ActsAsEasyJournalized::EasyJournalizedMethods
      end

    end

    module EasyJournalizedMethods

      def self.included(base)
        base.class_eval do

          has_many :journals, :as => :journalized, :dependent => :destroy, :inverse_of => :journalized

        end
      end

      def clear_current_journal
        @current_journal = nil
      end

      def init_journal(user, notes = '')
        @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
      end

      # Returns the names of attributes that are journalized when updating the issue
      def journalized_attribute_names
        self.class.column_names - self.journalized_options[:non_journalized_columns]
      end

      private

      def create_journal
        if @current_journal
          @current_journal.save
        end
      end

    end
  end
end
EasyExtensions::PatchManager.register_rails_patch 'ActiveRecord::Base', 'EasyPatch::ActsAsEasyJournalized'
