module IdCardPrinterService
    class EmployerCardsGenerator

        def initialize(employer, layout, zip=false)
            @employer = employer
            @member_keys = @employer.members.pluck(:pb_entity_key)
            @layout = layout
            @zip = zip
        end

        def call
            IdCard::PrintData.where(pl_plan_key: @employer.pl_plan_key).destroy_all
            IdCardPrinterService::EmployerDataFormatter.new(@employer.pl_plan_key, @member_keys).call


            # card_futures.each(&:value)

            # max_retries = 60
            # retries = 0
            # finished = false

            # batch_process = BatchProcess.find(batch_id)
            # until finished || retries > max_retries
            #     # Solid Queue stores finished jobs here if preserve_finished_jobs = true
            #     if batch_process.completed_jobs < batch_process.total_jobs
            #         sleep 0.5
            #         retries += 1
            #     else
            #         batch_process.destroy!
            #         finished = true
            #     end
            # end

            IdCard::PrintData.where(pl_plan_key: @employer.pl_plan_key, primary_mb_member_key: nil).destroy_all


            pdf_array = IdCardPrinterService::PdfProcessor.new(@employer, @layout, @zip).call

            group_pdfs = combine_pdfs(pdf_array)
            group_pdfs

        end

        private

        def combine_pdfs(pdf_array)
            if @zip
                group_cards_pdf = Zip::OutputStream.write_buffer do |zio|
                    pdf_array.each do |file|
                        zio.put_next_entry(file[:name])
                        zio.write(file[:data])
                    end
                end
            else
                group_cards_pdf = CombinePDF.new
                pdf_array.each { |pdf| group_cards_pdf << pdf }
            end
            group_cards_pdf
        end
    end
end
