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

public class CinemachineShake : MonoBehaviour
{
    [SerializeField]
    private CinemachineVirtualCamera _virtualCamera;
    private CinemachineVirtualCamera virtualCamera
    {
        get {
            if (_virtualCamera == null) {
                _virtualCamera = GetComponent<CinemachineVirtualCamera>();
            }
            return _virtualCamera;
        }
    }

    [SerializeField]
    private CinemachineBasicMultiChannelPerlin _cinemachineBasicMultiChannelPerlin;

    private CinemachineBasicMultiChannelPerlin cinemachineBasicMultiChannelPerlin {
        get {
            if (_cinemachineBasicMultiChannelPerlin == null) {
                _cinemachineBasicMultiChannelPerlin = virtualCamera.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
            }
            return _cinemachineBasicMultiChannelPerlin;
        }
    }

    private float shakeTimer;
    private float shakeTimerTotal;
    private float startingIntensity;
    
    public bool decreasingIntensity = false;

    [SerializeField]
    private float basicIntensity = 5.0f;
    [SerializeField]
    private float basicTime = 0.1f;

    private void Update()
    {
        if (decreasingIntensity) {
            UpdateForDecreasingIntensity();
        } else {
            UpdateForInstant();
        }
    }

    private void UpdateForDecreasingIntensity()
    {
        if (shakeTimer > 0) {
            shakeTimer -= Time.deltaTime;
            cinemachineBasicMultiChannelPerlin.m_AmplitudeGain = Mathf.Lerp(startingIntensity, 0.0f, 1 - (shakeTimer / shakeTimerTotal));
        }
    }

    private void UpdateForInstant()
    {
        if (shakeTimer > 0) {
            shakeTimer -= Time.deltaTime;
            if (shakeTimer < 0) {
                cinemachineBasicMultiChannelPerlin.m_AmplitudeGain = 0.0f;
            }
        }
    }

    public void ShakeCamera(float intensity, float time)
    {
        if (virtualCamera == null) {
            return;
        }
        cinemachineBasicMultiChannelPerlin.m_AmplitudeGain = intensity;
        shakeTimer = time;
        shakeTimerTotal = time;
        startingIntensity = intensity;
    }

    public void BasicInstantShakeCamera()
    {
        decreasingIntensity = false;
        ShakeCamera(basicIntensity, basicTime);
    }

    public void BasicDecreaseIntensityShakeCamera()
    {
        decreasingIntensity = true;
        ShakeCamera(basicIntensity, basicTime);
    }
}
