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

public static class ScreenShake{

    static CinemachineBrain brain;
    static CinemachineVirtualCamera vCam;
    static ScreenShakeUpdate shakeUpdate;

    class ScreenShakeUpdate : MonoBehaviour {
        [HideInInspector] public float shakeTimer;
        [HideInInspector] public float shakeTimerTotal;
        [HideInInspector] public float startingIntensity;

        void Update(){
            if (shakeTimer > 0){
                shakeTimer -= Time.deltaTime;
                CinemachineBasicMultiChannelPerlin multiChannelPerlin = vCam.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
                multiChannelPerlin.m_AmplitudeGain = Mathf.Lerp(startingIntensity, 0f, 1 - (shakeTimer / shakeTimerTotal));
            }
        }
    }

    public static void Shake(float intensity, float time){
        if(brain == null || shakeUpdate == null){
            brain = Camera.main.GetComponent<CinemachineBrain>();
            vCam = Camera.main.GetComponent<CinemachineBrain>().ActiveVirtualCamera.VirtualCameraGameObject.GetComponent<CinemachineVirtualCamera>();
            shakeUpdate = new GameObject("ShakeUpdate").AddComponent<ScreenShakeUpdate>();
        }

        CinemachineVirtualCamera currentCam = brain.ActiveVirtualCamera.VirtualCameraGameObject.GetComponent<CinemachineVirtualCamera>();
        if (vCam == null || vCam != currentCam){
            vCam = currentCam;
        }
        shakeUpdate.startingIntensity = 2.5f;
        shakeUpdate.shakeTimer = shakeUpdate.shakeTimerTotal = .25f;
    }
}
