using Controller.Bicycle;
using UnityEngine;
using Valve.VR.InteractionSystem;

namespace Wheels
{
    public class SwitchColliderOnStanding : MonoBehaviour
    {
        public RbBicycleController bikeController;
        public Collider whenStanding;
        public Collider[] whenDriving;
        [Range(0f, 5f)] public float speedThreshold = 0.5f;
        public bool rbToKinematicWhenStanding = true;

        private float lastFrameSpeed = -1f;

        // Update is called once per frame
        void Update()
        {
            var thisFrameSpeed = bikeController.CurrentSpeed;
            if (lastFrameSpeed >= 0f
                && (lastFrameSpeed <= speedThreshold && thisFrameSpeed <= speedThreshold
                    ||
                    lastFrameSpeed > speedThreshold && thisFrameSpeed > speedThreshold))
            {
                //no change
                return;
            }

            if (thisFrameSpeed <= speedThreshold)
            {
                if (rbToKinematicWhenStanding) bikeController.rigidBody.isKinematic = true;
                whenStanding.enabled = true;
                whenDriving.ForEach(c => c.enabled = false);
            }
            else
            {
                if (rbToKinematicWhenStanding) bikeController.rigidBody.isKinematic = false;
                whenStanding.enabled = false;
                whenDriving.ForEach(c => c.enabled = true);
            }
        }
    }
}