using UnityEngine;
using UnityEngine.EventSystems;

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

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

		[SerializeField] private Vector2 aspectRatio = new(10, 15);

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

			if (EventSystem.current?.currentSelectedGameObject) return;

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

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

			if (_isResizing && Input.GetMouseButton((int)mouseButton) && _resizeDirection != Vector2.zero) {
				float ratio = aspectRatio.x / aspectRatio.y;

				Vector2 delta = new(
					Event.current.mousePosition.x - _targetPosition.x,
					Event.current.mousePosition.y - _targetPosition.y
				);

				AppWindowUtility.ResizeWindowRelative(delta.x, delta.y, _resizeDirection, ratio);

				_targetPosition = Event.current.mousePosition;

				if (_resizeDirection.x < 0)
					_targetPosition.x -= delta.x;
				if (_resizeDirection.y > 0)
					_targetPosition.y -= delta.y;
			}
		}
	}
}