using System.Collections;
using ftt.Core.Managing;
using UnityEngine;

public class Phase2Handler : MonoBehaviour, ILeverMoveable
{
    [SerializeField] GameObject door1StartPos;
    [SerializeField] Transform door1UpPos;
    [SerializeField] Transform door1EndPos;
    [SerializeField] float lerpTime;

    bool isActivated = false;

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

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

    Vector3 startPos, midPos;
    #endregion

    private void OnTriggerEnter(Collider other)
    {
        if (isActivated) { return; }

        if (other.CompareTag("Player"))
        {
            isActivated = true;

            GameManager.GetManager.SoundsHandler.PlayOneShot(ftt.Core.Sounds.GameAudioClip.DoorOpening);

            door1StartPos.transform.position = door1EndPos.position;
        }
    }

    IEnumerator MoveDoorToEndPos(Vector3 endPos)
    {
        bool moving = true;
        float startTime = Time.time;

        while (moving)
        {
            Vector3 targetPos = endPos;

            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;

            door1StartPos.transform.position = p012;

            yield return null;
        }

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

    public void MoveObject()
    {
        StartCoroutine(MoveDoorToEndPos(door1UpPos.position));
    }
}
