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 add_bot
    if self.occupied?
      return "Failed to add Bot seat full"
    else
      # self.reload
      if self.player == nil
        # add player to game
        @bot_player = self.table.current_game.players.new(is_bot: true)
        # @bot_player = self.table.current_game.add_player_from_user(current_user).id
        self.player = @bot_player
        self.player.save
        self.save
        return "Added Bot"
      else
        self.player.is_bot = true
        self.player.save
        return "Added Bot"
      end

        return "Failed to add Bot"
    end
  end

  def remove_bot
    if !self.occupied?
      return "Failed to remove Bot seat empty"
    else
      if self.player.is_bot?
        self.player.is_bot = false
        self.player.save
        return "Removed Bot"
      end

      return "Failed to remove Bot"
    end
  end

  def empty
    self.player.user = nil
    self.player.soft_token = nil
    self.player.is_bot = false
    self.player.save
    self.user_id = nil
    self.user_soft_token = nil
    # self.player_id = nil
    self.save
    return "Successfully stood up."
  end

  def remove_player
    if !self.player
      return "No player to remove"
    else
      self.player.destroy
      self.user_id = nil
      self.user_soft_token = nil
      # self.player_id = nil
      self.save
      return "Successfully removed player"
    end
  end

  def occupied?
    self.user_id.present? || self.user_soft_token.present? || self.try("player").try("is_bot?") == true
  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
