class Dunlop::DashboardController < Dunlop::ApplicationController
  def home
  end

  def badge_info
    @process_class = params[:resource].to_s.classify.safe_constantize
    return head(:not_found) unless @process_class.present?
    if params[:id].present?
      setup_badge_info_for_record
    else
      if @process_class.ancestors.include?(WorkflowInstance)
        setup_badge_info_for_scenario
      else
        setup_badge_info_for_subprocess
      end
    end
    render layout: false
  end

  def changelog
    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
    changelog_path = Rails.root.join('CHANGELOG.md')
    render text: "No changelog present" unless File.exist?(changelog_path)
    source = File.read(changelog_path)
    source.gsub!(/(?<!\\)_/, '\_') # underscores are preserved
    html = markdown.render source
    html = "<div class='ui container'>#{html}</div>"
    render html: html.html_safe, layout: true
  end

  # POST /archived_mode
  def archived_mode
    session[:archived_mode] = true
    redirect_to main_app.root_path
  end

  # POST /active_mode
  def active_mode
    session[:archived_mode] = false
    redirect_to main_app.root_path
  end

  private

  def workflow_instances_scope(scope_options = {})
    scope_options[:archived] = session[:archived_mode] if can?(:archive, @record_class) and not scope_options[:all].present?
    @record_class.scope_for(current_user, scope_options)
  end

  def setup_badge_info_for_record
    @record = @process_class.find(params[:id])
    authorize! :read, @record
  end

  def setup_badge_info_for_scenario
    @record_class = @process_class
    @record_batch_class = @record_class.batch_class
    @workflow_instances = workflow_instances_scope.where(state: params[:state])
  end

  def setup_badge_info_for_subprocess
    # @process_class is a subprocess, so only show workflow_instances
    # belonging to this subprocess
    @record_class = WorkflowInstance # no type preference, depends on subprocess
    @workflow_instances = workflow_instances_scope.joins(@process_class.process_name.to_sym).where(@process_class.table_name => {sti_type: @process_class.name, state: params[:state]})
    if params[:workflow_instance_batch_id].present?
      # Limit query for to specific batch
      @workflow_instance_batch = WorkflowInstanceBatch.find(params[:workflow_instance_batch_id])
      @workflow_instances = @workflow_instances.where(workflow_instance_batch_id: @workflow_instance_batch.id)
    end
  end
end
