module JamRuby
  class BatchMailer < ActionMailer::Base
    include SendGrid
    layout "user_mailer"

    sendgrid_category :use_subject_lines
    sendgrid_unique_args :env => Environment.mode

    def _send_batch(batch, users)
      @batch_body = batch.body
      emails = users.map(&:email)

      sendgrid_recipients(emails)
      sendgrid_substitute(EmailBatch::VAR_FIRST_NAME, users.map(&:first_name))
      sendgrid_substitute('@USERID', users.map(&:id))

      batch.did_send(emails)

      mail(:to => emails, 
           :from => batch.from_email, 
           :subject => batch.subject) do |format|
        format.text
        format.html
      end
    end

    def send_batch_email(batch_id, user_id)
      user = User.find_by_id(user_id)
      batch = EmailBatch.find(batch_id)
      self._send_batch(batch, [user])
    end

    def send_batch_email_test(batch_id)
      batch = EmailBatch.find(batch_id)
      users = batch.test_users
      self._send_batch(batch, users)
    end

  end
end
