class State < ActiveRecord::Base
  belongs_to :sesh
  has_many   :questions
  has_many   :artists, through: :state_artists
  has_many   :state_artists
  has_many   :operas, through: :state_operas
  has_many   :state_operas

  def selection(selected, not_selected)
    selected.update_attributes(selected: true)
    not_selected.update_attributes(selected: false)
    update_question(selected)
    update_question(not_selected)
  end

  def update_question(question)
    self.questions << question
    update_artists(question)
    update_operas(question)
  end

  def update_artists(question)
    question.artists.each do |artist|
        state_artist = StateArtist.find_or_create_by(artist_id: artist.id, state_id: self.id)
      state_artist.times_offered += 1
      state_artist.times_selected += 1 if question.selected
      state_artist.save
    end
  end

  def update_operas(question)
    state_opera = StateOpera.find_or_create_by(opera_id: question.opera.id, state_id: self.id)
    state_opera.times_offered += 1
    state_opera.times_selected += 1 if question.selected
    state_opera.save
  end

  def average_num_of_questions_per_user
    num_of_seshes = Sesh.where("state_id = ?", self.id).length.to_f
    num_of_questions = self.questions.length.to_f
    return (num_of_questions / num_of_seshes).round(2)
  end

  def percent_of_opera_fans
    total_num_of_seshes = Sesh.all.length.to_f
    seshes_by_state = Sesh.where("state_id = ?", self.id).length.to_f
    return (seshes_by_state / total_num_of_seshes * 100).round(2)
  end
end
