require 'prawn'

module P4WebGUI
  class PDFCreator
    def initialize(folder)
      @folder = folder
    end
    
    def create_pdf(log, duration, breaches)
      status_color = '777777'
      highlight_color = '008B00'

      log.gsub!('&lt;', '<')
      log.gsub!('&gt;', '>')
      log.gsub!(/\<[bh]r\>/, "\n")
      log.gsub!(/\<[^\>]+\>/, '')
      log.gsub!(/(Info:)/, "<color rgb='#{status_color}'>\\1</color>")
      log.gsub!(/(Success!)/, "<color rgb='#{highlight_color}'>\\1</color>")

      number_of_breaches = breaches.inject(0) do |number, breach|
        number += 1 if breach.match(/Successful/)
        number
      end

      header = "<color rgb='#{status_color}'>NUMBER OF SECURITY BREACHES:</color> #{number_of_breaches}\n"
      header += "<color rgb='#{status_color}'>DURATION:</color> #{duration} SEC\n"
      header += "<color rgb='#{status_color}'>BREACHES LIST:</color>\n"
      breaches.each do |breach|
        header += "  <color rgb='#{status_color}'>-</color> #{breach}\n"
      end

      folder = @folder
      filename = "#{Time.now.to_i.to_s}.pdf"
      Prawn::Document.generate(File.join(folder, 'reports', filename), {
        :Title => "Evader Log #{Time.now}",
        :Author => "Stonesoft",
        :Creator => "Stonesoft",
        :CreationDate => Time.now
      }) do
        bounding_box([0, 690], :width => 500) do
          text "#{header}\n\n", :inline_format => true
          text "<color rgb='#{status_color}'>LOG:</color>\n#{log}", :inline_format => true
        end

        repeat(:all) do
          bounding_box([-40, 760], :width => 700) do
            image File.join(folder, 'images', 'header.png'), :fit => [620, 51]
          end
        end
      end
      filename
    end
  end
end