module JamRuby
  class GearSetupReminder

    @@log = Logging.logger[GearSetupReminder]

    def self.send_reminders
      begin
        cutoff_date = Date.parse(Rails.application.config.gear_setup_reminders_effective_from_date) # Define a cutoff date for the survey/gear setup emails

        reminder1_users(cutoff_date).find_each(batch_size:100) do |user|
          UserMailer.gear_setup_reminder1(user).deliver_now
          User.where(id: user.id).update_all(gear_setup_reminder1_sent_at: Time.now)
        end

        reminder2_users(cutoff_date).find_each(batch_size:100) do |user|
          UserMailer.gear_setup_reminder2(user).deliver_now
          User.where(id: user.id).update_all(gear_setup_reminder2_sent_at: Time.now)
        end

        reminder3_users(cutoff_date).find_each(batch_size:100) do |user|
          UserMailer.gear_setup_reminder3(user).deliver_now
          User.where(id: user.id).update_all(gear_setup_reminder3_sent_at: Time.now)
        end
      rescue Exception => e
        @@log.error("unable to send GearSetupReminder email #{e}")
        puts "unable to send GearSetupReminder email #{e}"
      end
    end

    def self.prospect_users
      User.where("users.first_certified_gear_at IS NULL")
    end

    def self.reminder1_users(cutoff_date)
      GearSetupReminder.prospect_users.where("users.created_at < ? AND users.created_at > ? AND users.gear_setup_reminder1_sent_at IS NULL", 1.day.ago, cutoff_date)
    end

    def self.reminder2_users(cutoff_date)
      GearSetupReminder.prospect_users.where("users.created_at < ? AND users.created_at > ? AND users.gear_setup_reminder1_sent_at IS NOT NULL AND users.gear_setup_reminder2_sent_at IS NULL", 3.days.ago, cutoff_date)
    end

    def self.reminder3_users(cutoff_date)
      GearSetupReminder.prospect_users.where("users.created_at < ? AND users.created_at > ? AND users.gear_setup_reminder2_sent_at IS NOT NULL AND users.gear_setup_reminder3_sent_at IS NULL", 5.days.ago, cutoff_date)
    end

  end
end