/**
 *  Round class:
 *  The Round class represents the matchups in a single round of a
 *  tournament.
 *
 *  @author Alyce Brady
 *  Creation Date: Fall 2025
 */


public class Round extends K_SimpleAL<Matchup>
{

    /** Finds the given participants and updates their most recent scores.
     *    @param p1  the participant with the higher ranking
     *    @param score1 p1's score in the most recent match-up
     *    @param p2  the participant with the lower ranking
     *    @param score2 p2's score in the most recent match-up
     *    @return true if the match was found and updated; false otherwise
     */
    public boolean updateScore(ParticipantInfo p1, int score1,
                               ParticipantInfo p2, int score2)
    {
        // Find the matchup involving p1 and p2.
        Matchup m = find(p1, p2);
        if ( m != null )
        {
            // Correct match found. Record the participants' scores.
            m.recordScores(score1, score2);
            return true;
        }

        // Match not found. Are participants in wrong order?
        if ( (m = find(p2, p1)) != null)
        {
            // Match found, but participants in opposite order.
            m.recordScores(score2, score1);
            return true;
        }

        // There was no matchup with these two participants at all.
        return false;
    }

    /** Returns a list of all of the winners in the current round.
     *  If a match has a tie (not an expected scenario), the "winner" is
     *  the first participant listed for that match.
     *      @return list of winners
     */
    public K_SimpleList<ParticipantInfo> getWinners()
    {
        K_SimpleAL<ParticipantInfo> winners = new K_SimpleAL<>();

        for (Matchup m : this )
            winners.add(m.getWinner());

        return winners;
    }

    /** Prints match-ups (with scores, if the match has been played).
     */
    public void printMatchups()
    {
        for ( Matchup m : this)
        {
            System.out.println(m);
        }
    }

    /** Finds a match (if any) with the given participants as participants
     *  1 and 2 (in that order).
     *    @param p1 the participant to look for as participant 1
     *    @param p2 the participant to look for as participant 2
     *    @return a match with the given participants in that order; or
     *            null if no such match exists in this round
     */
    private Matchup find(ParticipantInfo p1, ParticipantInfo p2)
    {
        for (Matchup m : this )
            if ( m.getParticipant1().equals(p1) &&
                 m.getParticipant2().equals(p2) )
            {
                    return m;
            }

        // Not found.
        return null;
    }

}
