require 'active_record'

module MailRotator
  class MailerStore < ActiveRecord::Base
    self.table_name = "mail_rotator_mailer_stores"

    validates :name, :limit, :sent_count, presence: true
    validates :name, uniqueness: true

    after_save :activate_next_mailer
    after_save :deactivate_other_mailers

    def activate
      update_attributes(active: true)
    end

    def increment
      new_count = sent_count + 1
      update_attributes(sent_count: new_count, active: true)
    end

    def reset
      update_attributes(sent_count: 0, active: false)
    end

    def over_limit?
      sent_count >= limit
    end

    private

    def activate_next_mailer
      return if active
      next_mailer = self.class.where("id > ?", id).first || self.class.first
      next_mailer.update_attributes(sent_count: 0, active: true)
    end

    def deactivate_other_mailers
      return unless active
      self.class.where("id != ?", id).update_all(active: false)
    end
  end
end
