class EmployerCardsGenerator

    def initialize(employer, layout)
        @employer = employer
        @layout = layout
    end

    def call
        SampleIdCard.where(employer_name: @employer.id_card_display_name).destroy_all
        EmployerCards::DataFormatter.new(@employer).call

        if @layout == "FullPageCard"
            group_cards_pdf_array = []
            reprint = Vhcs::HlidCardEggData.where(group_number: @employer.group_number).pluck(:family_id)
            SampleIdCard.where(employer_name: @employer.id_card_display_name).each do |card|
                if reprint.include?(card.family_id)
                    url = EmployerCards::JasperUrlGenerator.new(@employer, card.family_id, @layout).call
                    puts url
                    card_pdf = SampleCard::JasperPdfGenerator.new(url).call
                    card_filename = "#{card.name.gsub(", ","_")}_digital_card_#{Date.today}.pdf"
                    # group_cards_pdf_array.add(card_filename, pdf_object.to_pdf)
                    group_cards_pdf_array << { name: card_filename, data: card_pdf.to_pdf }
                end
            end

            # Initialize a string-based IO object
            group_cards_pdf = Zip::OutputStream.write_buffer do |zio|
                group_cards_pdf_array.each do |file|
                    zio.put_next_entry(file[:name])
                    zio.write(file[:data])
                end
            end
        else
            group_cards_pdf = CombinePDF.new
            reprint = Vhcs::HlidCardEggData.where(group_number: @employer.group_number).pluck(:family_id)
            SampleIdCard.where(employer_name: @employer.id_card_display_name).each do |card|
                if reprint.include?(card.family_id)
                    url = EmployerCards::JasperUrlGenerator.new(@employer, card.family_id, @layout).call
                    puts url
                    card_pdf = SampleCard::JasperPdfGenerator.new(url).call
        
                    group_cards_pdf << card_pdf
                end
            end
        end

        # todays_date = DateTime.current.strftime('%Y%m%d%H%M%S')
        # group_cards_pdf.save("tmp/#{@employer.name}_print_cards_#{todays_date}.pdf")

        group_cards_pdf
    end

end
