# it once was just Collection, but that intervenes with the rails lookup chain
module Dunlop::WorkflowStep::GenericCollection
  extend ActiveSupport::Concern
  #TODO: should this be part of the record_collection gem?
  def collection?
    true
  end

  def set_attributes_on_record(record, options = {})
    # Add the timestamp, user info if present and the notes to append
    change_time = options[:change_time] || Time.current
    if self.respond_to?(:notes) and record.respond_to?(:notes)
      record.append_note "\n#{change_time.iso8601} #{User.current.try(:email)}\n#{notes}".rstrip
    end

    record.attribute_change_time = change_time if record.respond_to?(:attribute_change_time)

    # Change the record's attributes and log the changes to its notes fields
    record.assign_attributes changed_attributes.except('notes')
  end

  # Used by set_attributes_on_record
  #def get_attribute_name_and_value_for(record, attr, value)
  #  if attr.end_with?('_id') && value.present?
  #    association_name = attr[0..-4]
  #    association_class = record.class.reflect_on_association(association_name).klass
  #    attribute_name = association_class.model_name.human
  #    if association = association_class.find_by(id: value)
  #      value = association.name if association.respond_to? :name
  #      value = association.title if association.respond_to? :title
  #    end
  #  else
  #    attribute_name = self.class.human_attribute_name(attr)
  #  end
  #  [attribute_name, value]
  #end

  def trigger_action!(action, attributes = nil)
    raise "Unsupported action #{action}" unless %w[process complete pending overdue reject].include?(action.to_s)
    assign_attributes attributes if attributes
    return false unless valid?
    change_time = Time.current
    each do |record|
      set_attributes_on_record record, change_time: change_time
      record.public_send("#{action}!")
    end
    true
  end
end
