using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Idleventures.Pooling;
using JetBrains.Annotations;
using UnityEngine;

public class Wave : PooledObject
{
    public Color InitialColor;
    public Color FinalColor;

    public float Scale;
    public float DefaultScale;

    public float BaseForce;

    public float Duration;

    public float Force
    {
        get
        {
            return ((BaseForce*Duration) * _currentDuration) / Duration;
        }
    }

    public event Action<Wave> OnWaveStart;
    public event Action<Wave> OnWaveDead;

    private SpriteRenderer _spriteRenderer;

    private float _currentDuration;

    private Coroutine _update;
    //private Rigidbody _rigidbody;

    #region Unity

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

    #endregion

    public void StartWave(Vector2 initialPoint,  float duration)
    {
        transform.position = initialPoint;
        transform.localScale = new Vector3(DefaultScale, DefaultScale, DefaultScale);

        gameObject.SetActive(true);
        
        Duration = duration;

        if (OnWaveStart != null)
            OnWaveStart(this);

        StopUpdate();
        _update = StartCoroutine(WaveUpdate());

        _spriteRenderer.color = InitialColor;
        _spriteRenderer.DOColor(FinalColor, Duration);        
    }

    public void DestroyWave()
    {
        if (OnWaveDead != null)
            OnWaveDead(this);
        
        ReturnToPool();

        StopUpdate();
        gameObject.SetActive(false);

        OnWaveDead = null;
    }

    private IEnumerator WaveUpdate()
    {
        _currentDuration = Duration;

        while (_currentDuration> 0)
        {
            //Do scale
            Vector3 newScale = transform.localScale + new Vector3(Scale, Scale, Scale);
            transform.localScale = newScale;

            _currentDuration -= 0.1f;
            
            yield return new WaitForFixedUpdate();
        }

        DestroyWave();
    }

    private void StopUpdate()
    {
        if (_update != null)
            StopCoroutine(_update);
    }
}