using System.Collections;
using UnityEngine;

namespace ftt.Puzzles
{
    public class MoveablePlatform : MonoBehaviour
    {
        [SerializeField] Transform gameobjectFinalPos;
        [SerializeField, Range(0f, 1f)] float lerpTime;

        bool isActivated = false;
        public bool IsActivated => isActivated;

        #region BEZIER_VARS
        float uCurrent = 0;
        float uMax = 1f;

        Vector3 p012 = Vector3.zero;
        bool moving;
        float startTime;

        Vector3 startPos, midPos;
        #endregion

        public void MovePlatform()
        {
            if (isActivated) { return; }

            isActivated = true;

            StartCoroutine(LerpTransform());
        }

        IEnumerator LerpTransform()
        {
            bool moving = true;
            float startTime = Time.time;

            while (moving)
            {
                Vector3 targetPos = gameobjectFinalPos.position;

                uCurrent = (Time.time - startTime) / lerpTime;

                if (uCurrent >= uMax)
                {
                    uCurrent = uMax;
                    moving = false;
                }

                Vector3 p01, p12;
                p01 = (1 - uCurrent) * startPos + uCurrent * midPos;
                p12 = (1 - uCurrent) * midPos + uCurrent * targetPos;

                p012 = (1 - uCurrent) * p01 + uCurrent * p12;

                transform.position = p012;

                yield return null;
            }

            uCurrent = 0;
            p012 = startPos = midPos = Vector3.zero;
        }
    }
}