module Mongoid
  module Sortable
    extend ActiveSupport::Concern

    included do
      field :sort_number, type: Integer

      after_initialize :set_sort_number
    end

    module ClassMethods
      def default_sort(sorted = true)
        if !sorted
          asc(:sort_number)
        else
          asc
        end
      end
    end

    private

    def set_sort_number
      if self.new? && self.sort_number.nil?
        last_record = self.class.desc(:sort_number).first
        if last_record && last_record.sort_number
          self.sort_number = (last_record.sort_number + 10) / 10 * 10
        else
          self.sort_number = 10
        end
      end
    end
  end
end
