namespace :mega_meme do
  desc 'Mega Meme generator'
  task generate: :environment do
    puts "#{Time.zone.now.to_s}: Starting MegaMeme generation"

    image_blobs = []

    (1..16).each do |n|
      eligible_meme = Meme
                      .left_joins(:votes)
                      .where('votes.created_at >= ?', 1.day.ago)
                      .where(slot: n)
                      .group(:id)
                      .order('COUNT(votes.id) DESC')
                      .first

      if eligible_meme
        image_blobs.push(ActiveStorage::Blob.service.send(:path_for, eligible_meme.file.key))
      else
        image_blobs.push(ActiveStorage::Blob.service.send(:path_for, Meme.find(Meme.pluck(:id)).sample.file.key))
      end
    end

    dir = Dir.mktmpdir

    MiniMagick::Tool::Montage.new do |image|
      image.geometry '250x250!+0+0'
      image.tile '4x4'
      image_blobs.each { |i| image << i }
      image << "#{dir}/output.png"
    end

    composed_meme = ComposedMeme.new
    composed_meme.save!
    composed_meme.file.attach(io: File.open("#{dir}/output.png"), filename: 'processed_image.png',
                              content_type: 'image/png')

    FileUtils.remove_entry(dir)

    puts "#{Time.zone.now.to_s}: Finished MegaMeme generation"
  end
end
