require “rubygems” require “twilio-ruby”

namespace :lesson_notifications do

desc "triggers daily email/sms notifications for newly available lessons"
task new_lessons: :environment do
  puts "STARTING: lesson_notifications:new_lessons task"
  now = Time.now
  Membership.active.each do |membership|
    membership.task_statuses.each do |task_status|
      next unless task_status.lesson? && task_status.notify_today?

      participant = task_status.participant
      content_module = task_status.task.bit_core_content_module
      application_name = I18n.t(:application_name, default: "ThinkFeelDo")

      if participant.notify_by_email?
        puts "sending daily lesson notifications for #{ now.wday } " \
             "on #{ now } for lesson module " \
             "'#{ content_module.plain_title }' " \
             "to participant #{ membership.participant.study_id }"
        next if ThinkFeelDoEngine::LessonNotificationMailer
                .lesson_notification_email(
                  participant_email: participant.email,
                  lesson_module: content_module,
                  application_name: application_name)
                .deliver_now

        next unless defined?(Raven)
        Raven.capture_message "failed to email lesson notification",
                              extra: {
                                membership: membership.try(:id),
                                participant: participant.try(:id),
                                content_module: content_module.try(:id)
                              }
      elsif participant.notify_by_sms?
        title = content_module.plain_title

        begin
          MessageSmsNotification
            .new(
              body: "Your next #{application_name} lesson is available: #{ title }!",
              phone_number: participant.phone_number)
            .deliver
        rescue StandardError => e
          next unless defined?(Raven)
          Raven.extra_context kind: "sms lesson notification",
                              membership: membership.try(:id)
          Raven.capture_exception e
          Raven::Context.clear!
        end
      else
        puts "ERROR: could not send new lesson notification due to no " \
             "contact_preference being set on participant " +
          task_status.participant.study_id.to_s
        next unless defined?(Raven)
        Raven.capture_message "no contact_preference set",
                              extra: {
                                membership: membership.try(:id)
                              }
      end
    end
  end
  puts "ENDING: lesson_notifications:new_lessons task"
end

end