module JamRuby
  class EmailBatchSet < ActiveRecord::Base
    self.table_name = "email_batch_sets"

    belongs_to :email_batch, :class_name => 'JamRuby::EmailBatch'
    belongs_to :user, :class_name => 'JamRuby::User'

    # def self.load_set(batch, user_ids)
    #   bset = self.new
    #   bset.email_batch_id = batch.id
    #   bset.user_ids = user_ids.join(',')
    #   bset.started_at = Time.now
    #   bset.batch_count = user_ids.size
    #   bset.save!
    #   bset
    # end

    def self.sent_email(batch, user_id)
      bset = self.new
      bset.email_batch_id = batch.id
      bset.user_id = user_id
      bset.started_at = Time.now
      bset.batch_count = 1
      bset.save!
      bset
    end

    def self.progress_set(batch, user, trigger_idx)
      bset = self.new
      bset.email_batch = batch
      bset.user = user
      bset.started_at = Time.now
      bset.batch_count = 1
      bset.trigger_index = trigger_idx
      bset.sub_type = batch.sub_type
      bset.save!
      bset
    end

    def self.scheduled_session_set(batch, receiver, sessions)
      bset = self.new
      bset.email_batch = batch
      bset.user = receiver
      bset.user_ids = sessions.map(&:id).join(',')
      bset.started_at = Time.now
      bset.batch_count = 1
      bset.save!
      bset
    end

    def self.new_musician_set(batch, receiver, new_musicians)
      bset = self.new
      bset.email_batch = batch
      bset.user = receiver
      bset.user_ids = new_musicians.map(&:id).join(',')
      bset.started_at = Time.now
      bset.batch_count = 1
      bset.save!
      bset
    end

    def subject
      unless sub_type.blank?
        return EmailBatchProgression.subject(self.sub_type.to_sym)
      end
      ''
    end

    def title
      unless sub_type.blank?
        return EmailBatchProgression.title(self.sub_type.to_sym)
      end
      ''
    end

    def previous_trigger_date
      return nil if 0 == self.trigger_index.to_i || self.user_id.nil?
      self.class
        .where(['email_batch__id = ? AND user_id = ? AND sub_type = ? AND trigger_index = ?',
                self.email_batch_id, self.user_id, self.sub_type, self.trigger_index - 1])
        .pluck(:created_at)
        .limit(1)
        .first
    end

  end
end
