using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpriteEffect : MonoBehaviour {
    public SpriteRenderer sr;
    public float deathTime = 3.0f;

    [Header("Color")]
    public bool doColor = true;
    public float colorDelay = 1.0f;
    public float colorTime = 2.0f;
    public Color startColor = Color.clear;
    public Color endColor = Color.white;

    [Header("Shake")]
    public bool doShake = true;
    public float shakeDelay = 2.0f;
    public float shakeStartPower = 4.0f;
    public float shakeEndPower = 0.0f;
    public float shakeDuration = 1.0f;
    public float shakeSpeed = 1.0f;

    Transform transf;

    private void OnEnable() {
        transf = transform;
        if(doColor) StartCoroutine(ColorIE());
        if(doShake) StartCoroutine(ShakeIE());
        StartCoroutine(KillIE());
    }

    public IEnumerator ColorIE() {
        float time = 0.0f;

        yield return new WaitForSeconds(colorDelay);

        while(time < colorTime) {
            time += Time.deltaTime;
            sr.color = Color.Lerp(startColor, endColor, time / colorTime);
            yield return null;
        }

        sr.color = endColor;

    }

    static Vector3 rotBuf;
    public IEnumerator ShakeIE() {
        float time = 0.0f;

        yield return new WaitForSeconds(shakeDelay);

        while(time < shakeDuration) {
            time += Time.deltaTime;
            rotBuf.x = 0.0f;
            rotBuf.y = 0.0f;
            rotBuf.z = Mathf.Lerp(shakeStartPower, shakeEndPower, time / shakeDuration) * Mathf.Cos(time * shakeSpeed);
            transf.localEulerAngles = rotBuf;

            yield return null;
        }

        transf.localEulerAngles = Vector3.zero;
    }

    public IEnumerator KillIE(){
        yield return new WaitForSeconds(deathTime);
        Destroy(gameObject);
    } 
}
