class Dunlop::WorkflowInstancesController < Dunlop::ApplicationController
  respond_to :html, :csv

  def reset
    authorize! :reset, WorkflowInstance
    @records = WorkflowInstance.find ids_param
    @records.each(&:reset!)
    redirect_path = @records.size == 1 ? [main_app, @records.first] : polymorphic_path([main_app, :selection, @records.first.try(:class) || WorkflowInstance], ids: ids_param.join(RecordCollection.ids_separator))
    redirect_back(fallback_location: redirect_path)
  end

  def categorize_as
    scenario_name = params[:scenario].to_s
    target_scenario_class = "WorkflowInstance::#{scenario_name.classify}".safe_constantize
    authorize! :categorize, target_scenario_class # general target authorization
    @records = WorkflowInstance.find ids_param
    @records.select{|r| can? :categorize, r }.each { |record| record.categorize_as scenario_name } # individual from authorization
    redirect_path = polymorphic_path([main_app, :selection, target_scenario_class], ids: ids_param.join(RecordCollection.ids_separator))
    respond_to do |format|
      format.js { render js: "window.location = '#{redirect_path}'" }
      format.html { redirect_to redirect_path }
    end
  end

  # POST /dunlop/workflow_instances/archive?ids=1~2~3~....
  def archive
    authorize! :archive, WorkflowInstance
    WorkflowInstance.where(id: ids_param).archive!
    session[:archived_mode] = true
    if ids_param and ids_param.size == 1
      redirect_to [main_app, WorkflowInstance.find_by(id: ids_param.first)]
    else
      redirect_to main_app.root_path
    end
  end

  # POST /dunlop/workflow_instances/revive?ids=1~2~3~....
  def revive
    authorize! :archive, WorkflowInstance
    WorkflowInstance.where(id: ids_param).revive!
    session[:archived_mode] = false
    if ids_param and ids_param.size == 1
      redirect_to [main_app, WorkflowInstance.find_by(id: ids_param.first)]
    else
      redirect_to main_app.root_path
    end
  end

  private

  def find_record
    @record = WorkflowInstance.find(params[:id])
  end
end
