using UnityEngine;
using UnityEngine.EventSystems;

namespace SatorImaging.AppWindowUtility {
	public class WindowGrabber : MonoBehaviour {
		public MouseButton mouseButton;

		private bool _isDragging;
		private Vector2 _targetPosition = Vector2.zero;
		private Vector2 _resizeDirection = Vector2.zero;

		private void Update() {
#if UNITY_EDITOR
			if (_isDragging.Equals(_isDragging)) return; // to avoid CS0162 warning
#endif

			if (EventSystem.current?.currentSelectedGameObject) return;

			if (Input.GetMouseButtonUp((int)mouseButton)) _isDragging = false;

			if (Input.GetMouseButtonDown((int)mouseButton)) {
				_targetPosition = Event.current.mousePosition;
				_resizeDirection =
					ResizeHelper.GetDirection(_targetPosition, new Vector2(Screen.width, Screen.height));
				_isDragging = true;
			}

			if (_isDragging && Input.GetMouseButton((int)mouseButton) && _resizeDirection == Vector2.zero) {
				// do NOT use Event.current.delta. it's sampled in local window coordinate.
				// and moving window while mouse dragging changes coordinate sample by sample.
				// just remove the gap between current mouse position and drag starting position.
				AppWindowUtility.MoveWindowRelative(
					(int)(Event.current.mousePosition.x - _targetPosition.x),
					(int)(Event.current.mousePosition.y - _targetPosition.y)
				);
			}
		}
	}
}