using System.Collections;
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.WebApi;
using Unity.VisualScripting;
using UnityEngine;

public class SlideDoor : Interactable
{
    bool IsOpen = false;
    bool opening = false;
    bool closing = false;
    float currentDuration;

    [SerializeField]
    private GameObject rightDoor;
    Vector3 rightDoorStart;
    Vector3 rightDoorEnd;

    [SerializeField]
    private GameObject leftDoor;
    Vector3 leftDoorStart;
    Vector3 leftDoorEnd;

    [SerializeField]
    private float lerpTime;
    [SerializeField]
    private AnimationCurve Curve;
    
    

    public void Start()
    {
        rightDoorStart = rightDoor.transform.position;
        Debug.Log(rightDoorStart);
        rightDoorEnd = rightDoor.transform.position;
        rightDoorEnd.z += 2;
        Debug.Log(rightDoorEnd);
        leftDoorStart = leftDoor.transform.position;
        Debug.Log(leftDoorStart);
        leftDoorEnd = leftDoor.transform.position;
        leftDoorEnd.z -= 2;
        Debug.Log(leftDoorEnd);
    }

    void Update()
    {
        if (opening)
        {
            currentDuration += Time.deltaTime;
            float t = currentDuration / lerpTime;
            rightDoor.transform.position = Vector3.Lerp(rightDoorStart, rightDoorEnd, Curve.Evaluate(t));
            leftDoor.transform.position = Vector3.Lerp(leftDoorStart, leftDoorEnd, Curve.Evaluate(t));

            if (currentDuration >= lerpTime)
            {
                currentDuration = 0;
                opening = false;
                rightDoor.transform.position = rightDoorEnd;
                leftDoor.transform.position = leftDoorEnd;
                IsOpen = true;
                Debug.Log("Door opened");
            }
        }
        else if (closing)
        {
            currentDuration += Time.deltaTime;
            float t = currentDuration / lerpTime;
            rightDoor.transform.position = Vector3.Lerp(rightDoorEnd, rightDoorStart, Curve.Evaluate(t));
            leftDoor.transform.position = Vector3.Lerp(leftDoorEnd, leftDoorStart, Curve.Evaluate(t));

            if (currentDuration >= lerpTime)
            {
                currentDuration = 0;
                closing = false;
                rightDoor.transform.position = rightDoorStart;
                leftDoor.transform.position = leftDoorStart;
                IsOpen = false;
                Debug.Log("Door closed");
            }
        }
    }

    public override void Interact()
    {
        if (!closing && !opening && !IsOpen)
        {
            opening = true;
        }
        else if (!closing && !opening && IsOpen)
        {
            closing = true;
        }
    }
    void OnTriggerExit(Collider other)
    {
        if(other.tag == "Player"&& IsOpen&& !opening)
        {
            closing=true;
        }
    }
}
