class WorkflowInstance::IndexCsvBuilder < CsvBuilder
  BASE_COLUMNS = %i[]

  def headers
    columns = [controller.record_class.model_name.human]
    columns += BASE_COLUMNS.map{|c| controller.record_class.human_attribute_name(c)}
    # Workflow steps
    workflow_step_mapping.each do |klass, attributes|
      columns << klass.model_name.human # state column
      columns += attributes.map{|attr| klass.human_attribute_name(attr)}
    end
    columns
  end

  def serialize_row(record)
    columns = [record.try(:presentation_name)]
    columns += BASE_COLUMNS.map{|c| record_attribute(record, c) }
    # Workflow steps
    workflow_step_mapping.each do |workflow_step_class, attributes|
      unless workflow_step = record.public_send(workflow_step_class.process_name)
        columns += Array.new(1 + attributes.size) # state + attributes Empty fill
        next
      end
      columns << workflow_step.state
      columns += attributes.map{|attr| record_attribute(workflow_step, attr) }
    end
    columns
  end

  # Create a mapping of (klass => attributes):
  #   {
  #     WorkflowStepClass => ['notes', 'workflow_step_action_executed', ...],
  #     ....
  #   }
  def workflow_step_mapping
    @workflow_step_mapping ||= begin
      controller.record_class.workflow_step_classes.each.with_object({}) do |klass, h|
        attributes = klass.collection.attributes.keys
        attributes -= ['notes'] unless options[:include_notes].present?
        h[klass] = attributes
      end
    end
  end

  def file_name
    "#{Rails.application.config.application_name}-export-#{date_number}.csv"
  end
end
