module Services
  # Class to analyze PDF to extract number of pages from a0 to a3 and costum qm
  class PdfAnalyzer
    require 'pdf/reader'
    require 'bigdecimal'

    attr_reader :costum_qm, :pages_a0, :pages_a1, :pages_a2, :pages_a3

    def initialize(file)
      @reader = PDF::Reader.new(file)

      @pages_a0 = 0
      @pages_a1 = 0
      @pages_a2 = 0
      @pages_a3 = 0
      @costum_qm = 0

      @page_width = 0
      @page_height = 0
    end

    def analyze
      @reader.pages.each do |page|
        format = extract_format(page)
        case format
        when 'a0'
          @pages_a0 += 1
        when 'a1'
          @pages_a1 += 1
        when 'a2'
          @pages_a2 += 1
        when 'a3'
          @pages_a3 += 1
        else
          @costum_qm += calculate_qm
        end
      end
    end

    private

    def calculate_qm
      (@page_width / 1000) * (@page_height / 1000)
    end

    def extract_format(page)
      # debugger
      extract_size(page)
      return 'a0'  if @page_width.round == 841 && @page_height.round == 1189
      return 'a1'  if @page_width.round == 594 && @page_height.round == 841
      return 'a2' if @page_width.round == 420 && @page_height.round == 594
      return 'a3' if @page_width.round == 297 && @page_height.round == 420

      'costum'
    end

    def extract_size(page)
      # debugger
      bbox   = page.attributes[:MediaBox] # CropBox
      width  = bbox[2] - bbox[0]
      height = bbox[3] - bbox[1]
      width_in_mm = pt2mm(width)
      height_in_mm = pt2mm(height)
      width_in_mm, height_in_mm = height_in_mm, width_in_mm if width_in_mm > height_in_mm

      @page_width = width_in_mm
      @page_height = height_in_mm

      nil
    end

    def pt2mm(pt)
      (pt2in(pt) * BigDecimal('25.4')).round(2)
    end

    def pt2in(pt)
      (pt / BigDecimal('72')).round(2)
    end
  end
end
