using System.Collections;
using UnityEngine;

public sealed class LaserEffectView : MonoBehaviour
{
    [SerializeField]
    private LineRenderer lineRenderer = null;
    [SerializeField]
    private float showTime = 1f;
    [SerializeField]
    private float scale = 1f;
    [SerializeField]
    private AnimationCurve showSize = AnimationCurve.EaseInOut(0, 0, 1, 1);
    [SerializeField]
    private EffectController hitEffectController = null;
    [SerializeField]
    private float hitDelay = 0.1f;

    public void Show(Vector3 startPosition, Vector3 endPosition, bool showHit = true) {
        gameObject.SetActive(true);
        StartCoroutine(ShowHitAnimation(startPosition, endPosition, showHit));
    }

    private IEnumerator ShowHitAnimation(Vector3 startPosition, Vector3 endPosition, bool showHit = false)
    {
        var timer = 0f;
        var hitTimer = hitDelay;
        while (timer < showTime)
        {
            var anim = timer / showTime;
            var aimPosition = Vector3.LerpUnclamped(startPosition, endPosition, anim);
            AnimateLine(transform.position, aimPosition, anim);
            timer += Time.deltaTime;
            hitTimer -= Time.deltaTime;
            if (hitTimer < 0 && showHit)
            {
                hitTimer += hitDelay;
                hitEffectController.Spawn(aimPosition);
            }
            yield return null;
        }
        gameObject.SetActive(false);
    }

    private void AnimateLine(Vector3 from, Vector3 to, float anim = 0)
    {
        lineRenderer.SetPosition(0, from);
        lineRenderer.SetPosition(1, to);
        var widht = showSize.Evaluate(anim) * scale;
        lineRenderer.startWidth = widht;
        lineRenderer.endWidth = widht;
    }

    private void Start()
    {
        lineRenderer.positionCount = 2;
        gameObject.SetActive(false);
    }

#if UNITY_EDITOR
    [ContextMenu("test effect")]
    private void Test()
    {
        Timer.Add(0.5f, () => {
            Show(transform.position + Vector3.forward * 20, transform.position + Vector3.forward * 20 + Vector3.up);
        });
    }
#endif
}
