class Team < ApplicationRecord
  has_and_belongs_to_many :players, dependent: :destroy

  has_many :games, dependent: :destroy
  belongs_to :season

  validates :season, uniqueness: {scope: [:name, :category]}

  def captain
    captain = Player.find(self.captainID)
    return captain
  end
  def destroy_with_players
    # Delete captain if he doesn't have any other team
    all_teams = []
    captain = Player.find(self.captainID)
    cap_teams = Team.where(captainID: self.captainID)
    all_teams = captain.teams #.each { |t| all_teams << t }
    cap_teams.each { |t| all_teams << t if !all_teams.include?(t) }

    captain.destroy if all_teams.count.eql?(1)

    # Delete associated players only if they don't belong to any other team
    self.players.each do |player|
      player.destroy if player.teams.count.eql? 1
    end

    # Now, delete the team
    destroy
  end
  def players_for_select
    array = Array.new
    array << [ "#{self.captain.name} #{self.captain.last_name}", self.captain.id] if !self.players.include? self.captain

    self.players.each do |p|
      array << [ "#{p.name} #{p.last_name}", p.id]
    end
    return array
  end
end
