using UnityEngine;

namespace ScrambleKit.FX
{
    public class CameraFX : MonoBehaviour
    {
        public float TraumaReductionRate = 1.5f;
        public float ShakeRotation = 5f;
        public float ShakeTranslate = 0.5f;
        public float ShakeSpeed = 10f;

        // Based on talk from Squirrel Eiserloh https://www.youtube.com/watch?v=tu-Qe66AvtY
        private static float trauma = 0f;  // range [0..1]
        
        public static void Shake(float newTrauma)
        {
            trauma = Mathf.Min(1f, trauma + newTrauma);
        }

        void Update()
        {
            float shake = trauma * trauma;
            DoShake(shake);

            trauma = Mathf.Max(0, trauma - Time.deltaTime * TraumaReductionRate);
        }

        private void DoShake(float shake)
        {
            float rot = shake * ShakeRotation * UnitRand(0);
            transform.localEulerAngles = new Vector3(0, 0, rot);

            float xoff = shake * ShakeTranslate * UnitRand(0.3f);
            float yoff = shake * ShakeTranslate * UnitRand(0.6f);

            transform.localPosition = new Vector3(xoff, yoff, 0);
        }

        private float UnitRand(float channel = 0f)
        {
            float perl = Mathf.PerlinNoise(Time.time * ShakeSpeed, channel);  // [0..1]
            return (perl * 2f) - 1f;
        }
    }
}