module Jekyll
  class PodConverter < Converter
    safe true
    priority :low

    def setup()
      @links = {}
      if @links.empty? then
        file = File.open("map_pod_links.txt")
        file.readlines.each do |line|
          (key, value) = line.strip.split(/\s+/)
          @links[key] = value
        end
      end
    end
    def matches(ext)
      ext =~ /^\.pod$/i
    end

    def output_ext(ext)
      ".html"
    end

    def convert(content)
      setup

      output = ""

      content.split(/\n\n+/).each do |paragraph|
        if paragraph.start_with?("  ") then
          output += "<pre>" + paragraph + "</pre>"
        else
          p = paragraph.strip
          if ! p.start_with?("=") then
            p = "<p>\n" + p + "</p>"
          end
          output += convert_paragraph(p)
        end
      end

      return output
    end

    def convert_paragraph(content)
      # replace links with caption
      content.gsub!(/L<([^\|>]*)\|([^>]*)>/) { |match|
        caption = $1
        link    = $2
        if @links.has_key?(link) then
          uri = @links[link]
          "<a href='#{uri}'>#{caption}</a>"
        else
          "<a href='#{link}'>#{caption}</a>"
        end
      }

      # replace simple links
      content.gsub!(/L<([^>]*)>/) { |match|
        if @links.has_key?($1) then
          uri = @links[$1]
          "<a href='#{uri}'>#{uri}</a>"
        else
          "<a href='#{$1}'>#{$1}</a>"
        end
      }

      # replace tags
      map = {
         /G<([^>]+?)>/                    => '<img src="/assets/images/\1"/>', # FIXME: make it configurable
         /B<([^>]+?)>/                    => '<strong>\1</strong>',
         /I<([^>]+?)>/                    => '<i>\1</i>',
         /P<[^>]+?>/                      => '',
         /`([^`]+?)`/                     => '<code>\1</code>',
         /=(end|begin)\s*html/            => '',
         /=(cut|pod)/                     => '',
         /=begin\s*text(.+?)=end\s*text/m => '<pre>\1</pre>',
         /=over/                          => '<ul>',
         /=item\s*\*/                     => '=item ',
         /=item\s*(.*)$/su                => '<li>\1</li>',
         /=back/                          => '</ul>',
         /=head([1234])\s(.+?)$/su        => '<h\1>\2</h\1>',
      }

      map.each do |pattern, match|
        content.gsub!(pattern, match)
      end
      return content
    end
  end
end
