using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using TMPro;
using Unity.Netcode;

public class GameController : NetworkBehaviour
{
    public GoalArea leftGoalArea;
    public GoalArea rightGoalArea;
    public TextMeshProUGUI leftScoreText;
    public TextMeshProUGUI rightScoreText;
    

    public int winGoals;
    public NetworkVariable<int> leftScore = new NetworkVariable<int>();
    public NetworkVariable<int> rightScore = new NetworkVariable<int>();

    public UnityEvent OnLeftScore;
    public UnityEvent OnRightScore;

    public UnityEvent OnGameWonLeft;
    public UnityEvent OnGameWonRight;
   

    public UnityEvent OnGameReset;


    // Start is called before the first frame update
    void Start()
    {
        leftGoalArea.OnGoalTriggered.AddListener(LeftScore);
        rightGoalArea.OnGoalTriggered.AddListener(RightScore);
        ResetGame();
    }


    void LeftScore()
    {
        OnLeftScore?.Invoke();
        leftScore.Value += 1;
        leftScoreText.text = leftScore.Value.ToString();
        CheckScore();
    }

    void RightScore()
    {
        OnRightScore?.Invoke();
        rightScore.Value += 1;
        rightScoreText.text = rightScore.Value.ToString();
        CheckScore();
    }

    void CheckScore()
    {
        if (leftScore.Value >= winGoals)
        {
            OnGameWonLeft?.Invoke();
        }
        else if (rightScore.Value >= winGoals)
        {
            OnGameWonRight?.Invoke();
        }
    }

    private void Update()
    {

        leftScoreText.text = leftScore.Value.ToString();
        rightScoreText.text = rightScore.Value.ToString();
    }


    public void ResetGame()
    {
        leftScore.Value = 0;
        rightScore.Value = 0;

        leftScoreText.text = leftScore.Value.ToString();
        rightScoreText.text = rightScore.Value.ToString();

        OnGameReset?.Invoke();
    }

   



}
