class WorkflowInstanceBatchesController < ApplicationController
  before_action :find_record, only: [:show, :edit, :update, :destroy]
  delegate :workflow_instance_batch_class, :workflow_instance_class, to: :class
  respond_to :html, :csv

  def index
    authorize! :read, workflow_instance_batch_class
    @q = workflow_instance_batch_class.search(query)
    @q.sorts = "plan_date ASC" if @q.sorts.empty?
    @records = @q.result.page(params[:page]).per(params[:per_page])
  end

  def new
    authorize! :manage, workflow_instance_batch_class
    @record = workflow_instance_batch_class.new
  end

  def with_mixed_bas_completeness
    @records = workflow_instance_batch_class.with_mixed_bas_load_states
  end

  def create
    @record = workflow_instance_batch_class.new(record_params)
    authorize! :manage, @record
    if @record.save
      redirect_to action: :index
    else
      render action: "new"
    end
  end

  def show
    authorize! :read, @record
    respond_with @record, record_class: workflow_instance_class, include_notes: params[:include_notes]
  end

  def edit
    authorize! :manage, @record
  end

  def update
    authorize! :manage, @record
    if @record.update record_params
      redirect_to action: :index
    else
      render action: :edit
    end
  end

  class << self
    def workflow_instance_batch_class
      return @workflow_instance_batch_class if @workflow_instance_batch_class
      parts = controller_path.split('/').map(&:classify)
      parts.pop until klass = parts.join('::').safe_constantize
      @workflow_instance_batch_class = klass
    end

    def workflow_instance_class
      return @workflow_instance_class if @workflow_instance_class
      @workflow_instance_class = workflow_instance_batch_class.name.sub('Batch', '').constantize
    end
  end
  helper_method :workflow_instance_batch_class
  helper_method :workflow_instance_class

  private

  def record_params
    params.require(workflow_instance_batch_class.name.underscore.gsub('/', '_')).permit(:name, :plan_date, :workflow_instance_manager_id)
  end

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

  def query
    params[:q]
  end
end
