module Dunlop::WorkflowStepModel
  extend ActiveSupport::Concern
  include Dunlop::WorkflowStepModel::StateMachine
  include Dunlop::ProcessIdentification
  include Dunlop::AttributeChangesTracking

  included do
    include Dunlop::CollectionLookup
    include Dunlop::WorkflowStepModel::NotesHandling
    belongs_to :workflow_instance, optional: true
    #include HasManyChangeEvents
  end

  #TODO: should this be part of the record_collection gem?
  def collection?
    false
  end

  # Reset the attributes defined on the collection to the default value of a new record
  # and set the state back to pending
  def reset!
    new_record = self.class.new
    collection_class.attributes.except('notes').each do |attr, clean_value|
      self[attr] = new_record[attr]
    end
    self.notes = "[RESET]"
    pending
  end

  # returns the scope for all the workflow steps in the same batch.
  # If the record has no batch an empty scope is returned.
  #   record = workflow_instance.contractor_service_window1_execution
  #   record.workflow_steps_in_batch_scope #=> All the ContractorServiceWindow1Execution workflow step records for the batch
  #   record.workflow_steps_in_batch_scope(:owner_initialization) #=> All the OwnerInitialization workflow step records for the batch
  def workflow_steps_in_batch_scope(workflow_step = process_name)
    klass = workflow_step.to_s.classify.constantize
    batch_id = workflow_instance.workflow_instance_batch_id
    return klass.none unless batch_id.present?
    klass.joins(:workflow_instance).where(workflow_instances: {workflow_instance_batch_id: batch_id})
  end

  # This method will be triggered if all the workflow intances
  # in the same batch are in a final state (completed, rejected).
  # To use this functionality, implment in the appropriate class
  def all_of_batch_are_in_final_state(workflow_instance_batch)
  end

  module ClassMethods
    def activate_dunlop!
      # for possible future use dealing with class settings using this module's methods
    end

    def scope_for(user, options = {})
      archived = !!options[:archived]
      #if user.service_provider_id.present?
        #joins(:migration).where(migrations: {service_provider_id: user.service_provider_id, archived: archived})
      #else
        #joins(:migration).where(migrations: {archived: archived})
      #end
      if archived
        joins(:workflow_instance).where.not(workflow_instances: {archived_at: nil})
      else
        joins(:workflow_instance).where(workflow_instances: {archived_at: nil})
      end
    end

    def final_states
      %w[completed rejected]
    end
  end
end
