require 'rouge'
require 'open-uri'
require 'uri'

class RemoteSnippet < Liquid::Tag
  def initialize(tag_name, text, tokens)
    super
    args = text.strip.split(' ', 3)
    @path = args[0]
    if args.length() > 2
      @type = args[1]
      @range = args[2]
    elsif args.length() > 1
      @type = args[1]
      @range = "all"
    else
      @type = "text"
      @range = "all"
    end
  end

  def render(context)
    title = context.registers[:site].config['title']
    prefix = context.registers[:site].config['gitbox_url']
    url = "#{prefix};a=blob_plain;hb=HEAD;f=#{@path}"
    pretty_url = "#{prefix};a=blob;hb=HEAD;f=#{@path}"
    content = ""
    if @range == "all"
      URI.open(url) {|f| content = f.read }
    else
      rangenums = @range.split(",", 2)
      first = 0
      second = 0
      if rangenums.length() == 2
        first = Integer(rangenums[0])
        second = Integer(rangenums[1]) - first
        URI.open(url) {|f| content = f.each_line.drop(first).take(second).join() }
      else
        first = Integer(rangenums[0])
        URI.open(url) {|f| content = f.each_line.drop(first).join() }
      end
    end
    snippet_type = "snippet"
    if @type == "direct"
      content = Kramdown::Document.new(content).to_html
      snippet_type = "page"
    else
      content = content.force_encoding("utf-8")
      formatter = Rouge::Formatters::HTMLLegacy.new
      lexer = Rouge::Lexer.find_fancy(@type, content)
      content = formatter.format(lexer.lex(content))
    end
    #content = CGI::escapeHTML(content)
    return """
#{content}
<p class=\"snippet_footer\">This #{snippet_type} was generated by #{title}'s <strong>source tree docs</strong>:
<a href=\"#{pretty_url}\">#{@path}</a>
</p>
      """
  end
end

Liquid::Template.register_tag('remote_snippet', RemoteSnippet)

