using System;
using UnityEngine;

public class FlagZone : MonoBehaviour
{
    public float TimeStayAttackers { get; private set; }
    public float TimeStayDefenders { get; private set; }
    private int occupDefenders;
    private int occupAttackers;
    public bool IsOccupBoth => (occupDefenders > 0) && (occupAttackers > 0);
    public bool IsNotOccup => (occupDefenders == 0) && (occupAttackers == 0);
    private float timeForWin;

    private void Start()
    {
        timeForWin = SettingsReader.Instance.GetSettings.TimeToWin;
        TimeStayAttackers = 0;
        TimeStayDefenders = 0;
        occupAttackers = 0;
        occupDefenders = 0;
    }
    private void OnTriggerEnter(Collider other)
    {
        switch (other.tag)
        {
            case "Defender":
                occupDefenders++;
                break;
            case "Attacker":
                occupAttackers++;
                break;
            default:
                print(other.tag);
                break;
        }
    }
    
    private void OnTriggerExit(Collider other)
    {
        switch (other.tag)
        {
            case "Defender":
                occupDefenders--;
                break;
            case "Attacker":
                occupAttackers--;
                break;
        }
    }
    private void Update()
    {
        if (IsOccupBoth || IsNotOccup)
        {
            TimeStayAttackers = 0;
            TimeStayDefenders = 0;
        }
        else if (occupAttackers > 0)
        {
            print("Atackers ocuppy flag");
            TimeStayAttackers += Time.deltaTime;
            GameManager._attackersTeam.AddGroupReward(Time.deltaTime* 0.1f);
            GameManager._defendersTeam.AddGroupReward(-Time.deltaTime* 0.1f);
            if (TimeStayAttackers > timeForWin)
            {
                GlobalEventManager.SendCaptureFlag(Team.Attackers);
                NullifyFlagCapture();
            }
        }
        else if (occupDefenders > 0)
        {
            print("Defenders ocuppy flag");
            GameManager._defendersTeam.AddGroupReward(+Time.deltaTime* 0.1f);
            TimeStayDefenders += Time.deltaTime;
            if (TimeStayDefenders > timeForWin)
            {
                GlobalEventManager.SendCaptureFlag(Team.Defenders);
                NullifyFlagCapture();
            }
        }
    }

    private void NullifyFlagCapture()
    {
        TimeStayAttackers = 0;
        TimeStayDefenders = 0;
    }
}
