class Dunlop::StateBadge
  attr_reader :context, :target, :state, :options
  def initialize(context, target, options = {})
    @context = context
    @target = target
    @target = target.object if target && target.respond_to?(:decorated?) && target.decorated?
    @options = options
    @state = options[:state] || target.try(:state) # allow hard setting of state, take current state otherwise
  end

  def link_to
    options[:link_to]
  end

  def valid?
    target.present? && state.present?
  end

  def underscored
    @underscored = target.class.name.underscore
  end

  # Code climate extraction
  def human_state_name
    state_name = target.class.human_state_name(state)
    state_name
  end

  def badge_data
    result = (options[:data] || {})
    result = result.merge(id: target.id, resource: underscored, state: state)
    result.merge!(target: link_to) if link_to.present?
    result
  end

  # Generate html as string in stead of a partial. This made the workflow_instances index page render a factor 4 faster
  def html
    #content = options[:link_to] ? context.link_to(inner_badge_html, options[:link_to]) : inner_badge_html
    content = inner_badge_html
    context.content_tag :span, content,
      class: "display-badge #{underscored.gsub(/\W/, ' ')} #{state}",
      data: badge_data
  end

  def inner_badge_html
    badge_name = context.t("display_badge", scope: underscored, default: Proc.new{ I18n.t('display_badge', scope: underscored.split('/').first, default: target.class.model_name.human) })
    %|<span class="pre-display"></span><span class="badge-name">#{badge_name}</span><span class="human-state">#{human_state_name}</span><span class="post-display">#{options[:state_append_text]}</span>|.html_safe
  end
end
