# -*- encoding : utf-8 -*-
module MarkdownHelper
 
 
  def m_img(s)
    
    id = s.gsub(/<usrimg:(\w+)>/, '\1').to_i
    
    ForumUserImage.find(id).image.large.url if ForumUserImage.exists?(id)
  end
 
  def markdown(text)
   
   text = text.gsub(/<usrimg:(\w+)>/){|s| m_img s}
   
   
   renderer = Redcarpet::Render::HTML.new({
          
          :hard_wrap => true
        })
        markdown = Redcarpet::Markdown.new(renderer, {
          :autolink => true,
          :no_intra_emphasis => true,
          :fenced_code_blocks => true,
          :gh_blockcode => true
        })
   
     syntax_highlighter(markdown.render(text)).html_safe
    
  end

  def syntax_highlighter(html)
    doc = Nokogiri::HTML(html)
    doc.css("code").each do |pre|
      pre.replace Pygments.highlight(pre.content.rstrip, :lexer => pre.attr("class"))
      
    end
    
    
    doc.to_s
    
   
  end
  
end