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

public class KnobController : MonoBehaviour
{
    [SerializeField] private MassController _massController;
    [SerializeField] private float _rotationDuration = 0.3f;
    [SerializeField] private Vector3[] _positions;

    private int _currentIndex = 0;
    private bool _isRotating = false;

    private void OnMouseDown()
    {
        if (_isRotating) return;

        RotateToNextPosition();

        if (_massController != null)
            _massController.SwitchUnit();
    }

    private void RotateToNextPosition()
    {
        _currentIndex++;

        if (_currentIndex >= _positions.Length)
            _currentIndex = 0;

        StartCoroutine(RotateTo(_positions[_currentIndex]));
    }

    private IEnumerator RotateTo(Vector3 targetEuler)
    {
        _isRotating = true;

        Quaternion start = transform.rotation;
        Quaternion end = Quaternion.Euler(targetEuler);

        float time = 0f;

        while (time < _rotationDuration)
        {
            time += Time.deltaTime;
            float t = time / _rotationDuration;

            transform.rotation = Quaternion.Slerp(start, end, t);
            yield return null;
        }

        transform.rotation = end;
        _isRotating = false;
    }
}
