module SnailMail
  class IMI
    class << self
      include SnailMail::Helpers

      def render_indicium(pdf, letter, indicium, x = bounds.width - 294, options = {})
        svg = Nokogiri::XML(indicium&.svg || (raise "no indicium?"))
        imi_el = svg % "image#imi-barcode"
        raise "no imi element?" unless imi_el.present?
        imi_href = imi_el["xlink:href"]
        raise "no IMI href???" unless imi_href.present?
        imi_png = Base64.decode64(imi_href.split(",", 2).last)
        raise "failed to decode imi png -_-" unless imi_png.present?
        pdf.image(
          StringIO.new(imi_png),
          at: [x + 79, pdf.bounds.top - 8],
          width: 51,
        )
        pdf.bounding_box([x, pdf.bounds.top - 11], width: 90, height: 45) do
          pdf.font_size(8)
          pdf.text("U.S. POSTAGE", style: :bold)
          pdf.text(letter.mailing_date.strftime("%m/%d/%Y")) unless options[:no_indicia_date]
          pdf.text(ActiveSupport::NumberHelper.number_to_currency(indicium.cost))
          pdf.text("LFP", style: :bold)
          pdf.font("f25") { pdf.text("#{Rails.env.production? ? "hackapost" : "DEV"}!/#{indicium.hashid}", size: 6.2) }
        end

        pdf.image(StringIO.new(WATERMARK), at: [x, pdf.bounds.top - 5], width: 121) if (wm = svg % "#watermark") && wm["visibility"] != "hidden"
      rescue StandardError => e
        render_no_indicium(pdf, letter, e.class == StandardError ? e.message : "#{e.class}: #{e.message}")
      end

      private

      def render_no_indicium(pdf, letter, reason)
        error_text = <<~EOT
          this shouldn't happen.
          please tell nora about #{letter.public_id} and #{letter.usps_indicium&.public_id || "nonexistent indicium!"} :-(
          "#{reason}"
        EOT

        pdf.image(
          image_path("no_indicium.png"),
          width: 144,
          at: [432 - 144, 288],
        )
        pdf.text_box(error_text, at: [256, 280], width: 90, height: 65, overflow: :shrink_to_fit, size: 8)
      end

      WATERMARK = Base64.decode64 <<~EOI
                                    [encoded data, 18516 characters]
                                  EOI
    end
  end
end
