class Language < ApplicationRecord
  include Base::Language

  has_many :students,
    inverse_of: :language,
    primary_key: :SLID,
    foreign_key: :LanguageID,
    dependent: :restrict_with_error

  STATES = [
    :indiana,
    :nebraska,
    :new_jersey,
    :california,
    :iowa,
    :new_york,
    :pennslyvania,
    :colorado,
    :kansas,
    :illinois
  ]

  attr_writer :code_field

  scope :by_default, -> { where.not(default: '') }
  scope :id_greater_than_0, -> { where(id: 1..Float::INFINITY) }

  scope :with_code, ->(code) do
    return unless code

    collection = all
    collection.each { |member| member.code_field = code }
    collection
  end

  def code
    public_send(@code_field)
  end

  def self.for_state(state, code=false)
    return nil unless STATES.include?(state)

    query = order(state).where('SLID > 0').where.not(state => '')
    code ? query.with_code(state) : query
  end

  def self.for_default(code=false)
    id_greater_than_0
      .by_default
      .order(:name)
      .with_code(code)
  end
end
