# -*- coding: utf-8 -*-
# create image by PlantUML http://plantuml.com/
#
# Copyright (c) tamoot <tamoot+tdiary@gmail.com>
# Distributed under the GPL
#

require 'uri'
require 'zlib'
require 'digest/md5'

module ::PlantUML
   module Deflate

      CHARS ||= ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a + ['-', '_']

      def self.compress(text)
         compressed = Zlib::Deflate.deflate(text, Zlib::BEST_COMPRESSION)
         compressed.chars.each_slice(3).map do |chars|
            append3bytes(chars[0].ord, chars[1]&.ord.to_i, chars[2]&.ord.to_i)
         end.join
      end

      private

      def self.append3bytes(b1, b2, b3)
         [
            b1 >> 2,
            ((b1 & 0x3) << 4) | (b2 >> 4),
            ((b2 & 0xF) << 2) | (b3 >> 6),
            b3 & 0x3F,
         ].map { |c| CHARS[c & 0x3F] || '?' }.join
      end
   end

end

def plantuml(text)
   html = %Q|<div class="plantuml">|

   begin
      uri = URI::parse( @conf['plantuml.server'] )
      uri.path.gsub!(/\/+$/, "")
      uri.path << '/png/' << PlantUML::Deflate::compress(text)
      html << %Q|<img src=#{uri}></img>|
   rescue
      html << %Q|Error: #{$!.message}|
   end

   html << %Q|</div>|

end

add_conf_proc('plantuml_server', 'PlantUMLサーバ') do
   if @mode == 'saveconf'
      @conf['plantuml.server'] = @cgi.params['plantuml.server'][0]
   end

   r = <<-_HTML
   <h3>Summary</h3>
   <p>The image is generated by using specified PlantUML server.</p>
   <h3>URL</h3>
   <p>Please specify the PlantUML server URL (official site or your own PlantUML server)
   <li> Official PlantUML server: http://www.plantuml.com/plantuml/</li>
   <p><input type="text" name="plantuml.server" size="100" value="#{@conf['plantuml.server']}"></p>
   _HTML

   r
end

