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

public class ShelfDoor : MonoBehaviour
{
    [SerializeField] private float maxOffset;
    private bool dragging;
    private float currentOffset;
    private Vector3 originalPosition;
    private Vector3 dragStartMouse;
    private bool fullyOpened;

    // Start is called before the first frame update
    void Start()
    {
        originalPosition = transform.position;
        dragging = false;
        fullyOpened = false;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnMouseDown()
    {
        dragStartMouse = UnityEngine.Camera.main.ScreenToWorldPoint(Input.mousePosition);
        currentOffset = transform.position.x - originalPosition.x;
        dragging = true;
        Debug.Log("Pressed");
    }

    private void OnMouseDrag()
    {
        if (dragging && !fullyOpened)
        {
            Vector3 drag = UnityEngine.Camera.main.ScreenToWorldPoint(Input.mousePosition);
            Vector3 newPosition = transform.position;
            float deltaX = drag.x - dragStartMouse.x;
            currentOffset += deltaX;
            if (currentOffset < 0)
            {
                newPosition = originalPosition;
            }
            else if (currentOffset > maxOffset)
            {
                newPosition = new Vector3(originalPosition.x + maxOffset, transform.position.y, transform.position.z);
                if (fullyOpened == false)
                {
                    fullyOpened = true;
                    LeanTween.moveX(gameObject, 15f, 1f);
                    Debug.Log("Fully opened");
                    Invoke("SwitchScene", 3f);
                }
            }
            else
            {
                newPosition = new Vector3(originalPosition.x + currentOffset, transform.position.y, transform.position.z);
            }
            if (!fullyOpened)
            {
                transform.position = newPosition;
                dragStartMouse = drag;
            }
        }
        
    }

    public void SwitchScene()
    {
        transform.parent.GetComponent<InteractiveModules.Waredrobe>().SwitchScene();
    }

    private void OnMouseUp()
    {
        dragging = false;
        Debug.Log("Released");
    }
}
