using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class PlayArea : GameEntity
{
    public int Damage = 1;
    public float DamageInterval = 1f;

    private float _nextPenalty;
    private List<PlayerController> _inside;
    private List<PlayerController> _outside;

    public void Awake()
    {
        _inside = new List<PlayerController>();
        _outside = new List<PlayerController>();
    }

    public void AddPlayerToPlayArea(PlayerController player)
    {
        if (!_inside.Contains(player))
        {
            _inside.Add(player);
        }

        if (_outside.Contains(player))
        {
            _outside.Remove(player);
        }
    }

    public void RemovePlayerFromPlayArea(PlayerController player)
    {
        if (!_outside.Contains(player))
        {
            _outside.Add(player);
        }

        if (_inside.Contains(player))
        {
            _inside.Remove(player);
        }
    }

    public void OnTriggerEnter(Collider col)
    {
        var playerController = col.GetComponentInParent<PlayerController>();

        if (playerController)
        {
            AddPlayerToPlayArea(playerController);
        }

    }

    public void OnTriggerExit(Collider col)
    {
        var playerController = col.GetComponentInParent<PlayerController>();
        if (playerController)
        {
            RemovePlayerFromPlayArea(playerController);
        }
    }

    public void Update()
    {
        if (Time.timeSinceLevelLoad > _nextPenalty)
        {
            foreach (var playerController in _outside)
            {
                playerController.Player.Damage(Damage, this);
            }

            _nextPenalty = Time.timeSinceLevelLoad + DamageInterval;
        }

    }

    public void SetSize(float gameGameRadius)
    {
        var boxCollider = GetComponent<BoxCollider>();
        if (boxCollider)
        {
            var size = Vector3.one * gameGameRadius;
            boxCollider.size = size;
        }
    }

    public static Vector3 GetSpawnPoint(Vector3 center, float radius, float angle)
    {
        Vector3 pos = Vector3.zero;
        pos.x = center.x + radius * Mathf.Sin(angle * Mathf.Deg2Rad);
        pos.z = center.z + radius * Mathf.Cos(angle * Mathf.Deg2Rad);
        pos.y = center.y;
        return pos;
    }
}
