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

public class StepKnob : MonoBehaviour
{

    public List<float> StepPositions;

    Vector2 _lastMousePos;
    bool _locked;
    [SerializeField]
    float _threshold;
    [SerializeField]
    Vector3 _localRotation;

    public int Value = 0;
    void Start()
    {
        var newRot = StepPositions[0];
        var locRot = transform.localRotation.eulerAngles;

        locRot.y = newRot;
        _localRotation.y = newRot;
        transform.localRotation = Quaternion.Euler(locRot);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit, 100.0f) && !_locked)
            {
               if (transform.name != hit.transform.name)
                {
                    _locked = false;
                    return;
                }
				if (Manager.Locked != "" && Manager.Locked != transform.name) {
					_locked = false;
                    return;
				}
                _locked = true;
				Manager.Locked = transform.name;
            }
            else if (!_locked)
            {
                return;
            }

            var mousePos = (Vector2)Input.mousePosition;
            if (_lastMousePos == Vector2.zero)
            {
                _lastMousePos = mousePos;
                return;
            }

            var delta = mousePos - _lastMousePos;
            var val = delta.x + delta.y;
            _threshold += val;
            if (Mathf.Abs(_threshold) > 35)
            {
                if (_threshold < 0) { Value++; }
                else if (_threshold > 0) { Value--; }

                if (Value >= StepPositions.Count)
                {
                    Value = StepPositions.Count - 1;
                }
                else if (Value < 0)
                {
                    Value = 0;
                }

                var newRot = StepPositions[Value];
                var locRot = transform.localRotation.eulerAngles;

                locRot.y = newRot;
                _localRotation.y = newRot;
                transform.localRotation = Quaternion.Euler(locRot);

                _threshold = 0;
            }
            _lastMousePos = mousePos;
        }
        else
        {
            Manager.Locked = "";
            _locked = false;
            _lastMousePos = Vector2.zero;
            _threshold = 0;
        }
    }
}
