class Seat < ActiveRecord::Base
  belongs_to :table
  belongs_to :game
  belongs_to :user
  belongs_to :player

  def sit(current_user)
    if self.occupied?
      return self
    else
      # Stand up from any other seats at this table
      current_user.stand_from(self.table)

      self.reload
      if self.player == nil
        self.player_id = self.table.current_game.add_player_from_user(current_user).id
      end

      self.player.user_id = current_user.id
      self.player.soft_token = current_user.soft_token
      self.player.save

      self.user_id = current_user.id
      self.user_soft_token = current_user.soft_token

      return self.save
    end
  end

  def stand(user)
    unless self.occupied_by?(user)
      return "Error. Seat not occupied by you."
    else
      # self.table.current_game.remove_player_from_user(user)
      self.player.user = nil
      self.player.soft_token = nil
      self.player.save
      self.user_id = nil
      self.user_soft_token = nil
      # self.player_id = nil
      self.save
      return "Successfully stood up."
    end
  end

  def occupied?
    self.user_id.present? || self.user_soft_token.present?
  end

  def occupied_by? user
    if user.id.present?
      self.user_id == user.id
    end
    if user.soft_token.present?
      self.user_soft_token == user.soft_token
    end
  end

  def user_display_name
    return nil unless self.occupied?
    self.user.try(:email) || "Guest" + self.user_soft_token.to_s[0..4]
  end
end
