module Dunlop::InterpretedTextHelper
  # taken from the g2l manual text helper
  def interpreted_text(text, options={})

    # internal references to other translation strings:
    #   ${models.plural.workflow_instance}
    # gets replaced by the value of the actual model
    text.scan(/\${[\w\.\/\-]+}/).each do |t_ref|
      if t_ref == '${application.name}'
        text.sub! t_ref, application_name
      else
        t_path = t_ref[2..-2]
        t_path.prepend 'activerecord.' if t_path.starts_with?('models.') or t_path.starts_with?('attributes.')
        t_path.prepend 'activerecord.state_machines.' if t_path.starts_with?('states.') # state_machine to simple notation
        text.sub! t_ref, t(t_path)
      end
    end

    # Use shorthand notation for images:
    #   $i{iom-capacity}        => image_tag("manual/iom-capacity.png")
    #   $i{image1|right;300px}  => <div style="float:right;width:300px">#{image_tag("manual/image1.png")}</div>
    #   $i{image2|200px}        => <div style="width:200px;display:inline-block">#{image_tag("manual/image2.png")}</div>
    text.scan(/\$i{[\w\/\.\-;0-9|]+}/).each do |image_ref|
      image_name, style_spec = image_ref[3..-2].split('|')
      image_name.prepend "manual/"
      image_name << ".png"
      image_html = image_tag(image_name)
      if style_spec.present?
        style_spec.gsub!(/(left|right)/, 'float:\1')
        style_spec.gsub!(/(\d+px)/, 'width:\1')
        style_spec += ";display:inline-block" unless style_spec =~ /float/
        image_html = "<div class='manual-image' style='#{style_spec}'>#{image_html}</div>"
      end
      text.sub! image_ref, image_html
    end
    text.html_safe
  end

  def interpreted_translation(path, options={})
    options[:default] ||= "missing manual entry #{path} for locale #{I18n.locale}"
    text = t(path, options)
    interpreted_text(text, options)
  end
end
