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

public class RotateKnob : MonoBehaviour
{

  public float Inverter = 1;
  public bool useRotationLimit = false;
  public Vector2 RotationLimits;
  public Vector3 RotationAxis;

  public float Sensitivity = 1f;
  Vector2 _lastMousePos;
  bool _locked;

  public float Value;
  public float ValueMin = -100;
  public float ValueMax = 100;

  [SerializeField]
  Vector3 _localRotation;

  void Start()
  {

  }

  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 locRot = transform.localRotation.eulerAngles;
      var val = delta.x + delta.y * Inverter;
      var newRot = Sensitivity * -val;
      var limitMinReached = false;
      var limitMaxReached = false;
      if (RotationAxis.x > 0)
      {
        locRot.x += newRot;
        limitMinReached = useRotationLimit && locRot.x < RotationLimits.x;
        limitMaxReached = useRotationLimit && locRot.x > RotationLimits.y;
        locRot.x = useRotationLimit ? Mathf.Clamp(locRot.x, RotationLimits.x, RotationLimits.y) : locRot.x;
      }
      else if (RotationAxis.y > 0)
      {
        locRot.y += newRot;
        limitMinReached = useRotationLimit && locRot.y < RotationLimits.x;
        limitMaxReached = useRotationLimit && locRot.y > RotationLimits.y;
        locRot.y = useRotationLimit ? Mathf.Clamp(locRot.y, RotationLimits.x, RotationLimits.y) : locRot.y;
      }
      else
      {
        locRot.z += newRot;
        limitMinReached = useRotationLimit && locRot.z < RotationLimits.x;
        limitMaxReached = useRotationLimit && locRot.z > RotationLimits.y;
        locRot.z = useRotationLimit ? Mathf.Clamp(locRot.z, RotationLimits.x, RotationLimits.y) : locRot.z;
      }
      Value += Sensitivity * -val * .1f;
      Value = limitMaxReached ? ValueMax : Value;
      Value = limitMinReached ? ValueMin : Value;

      Value = Value > ValueMax ? ValueMax : Value;
      Value = Value < ValueMin ? ValueMin : Value;
      _localRotation = locRot;
      transform.localRotation = Quaternion.Euler(locRot);
      _lastMousePos = mousePos;
    }
    else
    {
      Manager.Locked = "";
      _locked = false;
      _lastMousePos = Vector2.zero;
    }
  }
}
