using Kryz.CharacterStats.Examples;
using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnitDifficultySetter : MonoBehaviour
{
    [SerializeField] private GameEventListener_Player onPlayerJoinedParty;
    [SerializeField] private GameEventListener_Player onPlayerLeftParty;

    Health unitHealth;
    Mana unitMana;
    CharacterStats unitStats;

    private UnitDifficultySettings difficultySettings;

    bool initialized = false;

    private void Awake()
    {
        if (!PhotonNetwork.IsMasterClient) return;

        initialized = false;

        onPlayerJoinedParty.Response.AddListener((x) => UpdateDifficultyOnPlayerJoined());
        onPlayerLeftParty.Response.AddListener((x) => UpdateDifficultyOnPlayerLeft());


        unitHealth = GetComponentInParent<Health>();
        unitMana = GetComponentInParent<Mana>();
        unitStats = GetComponentInParent<CharacterStats>();
    }

    public void InitializeUnitDifficulty(UnitDifficultySettings difficultySettings)
    {
        this.difficultySettings = difficultySettings;

        unitHealth = GetComponentInParent<Health>();
        unitMana = GetComponentInParent<Mana>();
        unitStats = GetComponentInParent<CharacterStats>();

        this.difficultySettings.SetDifficulty(ref unitHealth, ref unitMana, ref unitStats);
        initialized = true;

        UpdateDifficultyByNumberOfPlayers(PhotonNetwork.CurrentRoom.PlayerCount - 1);
    }

    private void UpdateDifficultyOnPlayerJoined()
    {
        StartCoroutine(IncreaseDifficultyOnPlayerJoined());
    }
    private void UpdateDifficultyOnPlayerLeft()
    {
        StartCoroutine(DecreaseDifficultyOnPlayerJoined());
    }

    IEnumerator IncreaseDifficultyOnPlayerJoined()
    {
        yield return new WaitUntil(() => initialized == true);

        UpdateDifficultyByNumberOfPlayers(1);
    }
    IEnumerator DecreaseDifficultyOnPlayerJoined()
    {
        yield return new WaitUntil(() => initialized == true);

        UpdateDifficultyByNumberOfPlayers(-1);
    }

    private void UpdateDifficultyByNumberOfPlayers(int playerCount)
    {
        unitHealth.SetMaxValue((unitHealth.GetMaxValue() + (playerCount * unitHealth.GetBaseMaxValue())));
        unitHealth.ChangeValue(unitHealth.GetMaxValue());
    }
}
