using System;
using System.Collections;
using System.Collections.Generic;
using DarkTonic.MasterAudio;
using UnityEngine;
using Idleventures.Pooling;

public class Enemy : PooledObject
{        
    public float Duration;

    public event Action OnEnemySpawn;
    public event Action<GameObject> OnEnemyDisable;

    private Vector3 _currentEnemyPosition;
    private Rigidbody _rigidbody;

    public string ExplosionSound;

    #region Unity

    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody>();
    }

    private void Start()
    {
        if (Pool == null)
            Pool = ObjectPoolController.Instance.GetPool(this);
    }

    #endregion

    public void OnCollisionEnter(Collision _object)
    {        
        switch (_object.gameObject.tag)
        {
            case "Wave":
            //Debug.Log("WAVE");
            break;

            case "Player":
            //Debug.Log("Bateu no Player");

            //NOTE: Para chamar um novo som basta passar a string dele e o transform onde tocar ele.
            MasterAudio.PlaySound3DAtTransform(ExplosionSound, transform);

            _currentEnemyPosition = this.transform.position;                        
            WaveCreation.Instance.CreateWave(_currentEnemyPosition, Duration);
            Disable();                       
            break;

            default:
            //Debug.Log("Bateu no inimigo, switch default case.");
            _currentEnemyPosition = this.transform.position;
            
            MasterAudio.PlaySound3DAtTransform(ExplosionSound, transform);

            WaveCreation.Instance.CreateWave(_currentEnemyPosition, Duration);
            Disable();
            break;
        }
    }

    public void Enable()
    {
        this.gameObject.SetActive(true);
    }

    //Return to pool method.
    private void Disable()
    {
        if (OnEnemyDisable != null)
            OnEnemyDisable(gameObject);

        ReturnToPool();

        this.gameObject.SetActive(false);
    }

    //Add force to game object.
    private void AddForce(Vector2 force)
    {
        _rigidbody.AddForce(force, ForceMode.Impulse);
    }

    public void OnTriggerEnter(Collider other)
    {
        switch (other.gameObject.tag)
        {
            case "Wave":
            //UnityEngine.Debug.Log("Collision with wave.");

            Wave collisionWave = other.GetComponent<Wave>();

            Vector2 resul = this.transform.position - collisionWave.transform.position;
            Vector2 force = resul * collisionWave.Force;

            AddForce(force);
            break;

            default:
            break;
        }
    }

    public void OnTriggerExit(Collider other)
    {
        if (other.gameObject.CompareTag("CameraLimits"))
        {
            //Debug.Log("Recycle!");
            Disable();
        }
    }
}
