module SupportTools
  USER_BATCH_SIZE = 400

  class UserJob < SupportTools::Base
    attributes :id, :reporter, :reporter_email, :job_type, :users, :content, :description, :reason, :detailed_reason,
      :is_permanent, :skip_ip_ban, :grouped, :duration, :ban_partners, :ban_affiliates

    self.primary_attribute = :id

    def jobs
       return { "reactivate" => UndeleteJob, "deactivate" => DeleteJob, "tos_ban" => TOSJob, "tos_unban" => TOSJob, "force_password_reset" => ForcePasswordResetJob}
    end

    validates :job_type, :users, :reporter, presence: true
    validates :content, :description, :reason, :detailed_reason, :is_permanent, :skip_ip_ban, :duration, presence: true, if: :tos_ban?

    def user_logins_string
      users.split(/[\s,]+/)
    end

    def save
      return false unless valid?

      return false unless self.jobs[job_type]

      action
    end

    def action
      user_groups = user_logins_string.in_groups_of(USER_BATCH_SIZE, false)
      self.grouped = true if user_groups.length > 1

      user_groups.each do |user_group|
        job_options = {
          job_type: job_type,
          reporter: reporter,
          reporter_email: reporter_email,
          users: user_group,
          content: content,
          description: description,
          reason: reason,
          detailed_reason: detailed_reason,
          is_permanent: is_permanent,
          skip_ip_ban: skip_ip_ban,
          ban_partners: ban_partners,
          ban_affiliates: ban_affiliates,
          duration: duration
        }
        self.id = self.jobs[job_type].create(job_options)
      end
    end

    def tos_ban?
      job_type == "tos_ban"
    end
  end
end
