module JamRuby
  class DailyJob
    extend Resque::Plugins::JamLonelyJob

    @queue = :scheduled_daily_job
    @@log = Logging.logger[DailyJob]

    def self.perform
        @@log.debug("waking up")

        Teacher.randomize_order

        bounced_emails

        calendar_manager = CalendarManager.new
        calendar_manager.cleanup()

        MusicSession.cleanup_old_sessions


        @@log.debug("done")
    end

    def self.bounced_emails
      if APP_CONFIG.check_bounced_emails
        start = GenericState.bounce_check_at

        if start.nil?
          start = (Date.today - 1).to_s
        end

        end_date = Date.today.to_s

        @@log.info("checking bounced emails from #{start} to #{end_date}")

        bounces = SendgridToolkit::Bounces.new
        result = bounces.retrieve({start_date: start, end_date: end_date})

        result.each do |item|
          user = User.find_by_email(item["email"])
          if user
            User.where(id: user.id).update_all(subscribe_email: false, bounced: true)
          end
        end

        singleton = GenericState.singleton
        singleton.bounce_check_at = end_date
        singleton.save!
      end
    end
  end
end
