using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

[RequireComponent(typeof(Image))]
public class DragToInteractions : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
{
	public UIColorConfigurations colorConfig;
	private Vector3 originalPosition = Vector3.zero;
	private Image currentImage;
	private Color originalColor;
	private bool hold = false;
	private RectTransform rectTransform;

	public bool grabbable = false;
	private Vector2 parentXY0;
	private Vector2 parentXY1;
	public bool disableOutsideInteraction = true;

	private Vector2 mousePos;
	public System.Action<ResourceType> toDo;

	private void Start() {
		currentImage = GetComponent<Image>();
		originalColor = currentImage.color;
		rectTransform = GetComponent<RectTransform>();

		Vector3[] tempVectors = new Vector3[4];
		(rectTransform.parent as RectTransform).GetWorldCorners(tempVectors);

		parentXY0 = tempVectors[0];
		parentXY1 = tempVectors[2];
	}

	public void OnPointerEnter(PointerEventData eventData) {
		if (grabbable) { 
			currentImage.color = colorConfig.mouseOverColor;
		}
	}

	public void OnPointerExit(PointerEventData eventData) {
		if (grabbable) {
			currentImage.color = originalColor;
		}
	}

	public void OnPointerDown(PointerEventData eventData) {
		if (!CheckIfOutsideBlock() && grabbable) {
			hold = true;
			originalPosition = transform.localPosition;
			currentImage.color = colorConfig.selectedColor;
		}
	}

	public void OnPointerUp(PointerEventData eventData) {
		if (grabbable) {
			currentImage.color = colorConfig.mouseOverColor;
			hold = false;
		}
	}

	public void Release() {
		hold = false;
	}

	public bool CheckIfOutsideBlock() {
		mousePos = Input.mousePosition;
		if (disableOutsideInteraction) {
			if ((mousePos.x < parentXY0.x) || (mousePos.y < parentXY0.y)) {
				return true;
			}
			if ((mousePos.x > parentXY1.x) || (mousePos.y > parentXY1.y)) {
				return true;
			}
			return false;
		}
		return false;
	}

	void Update() {
		if (hold) {
			if (CheckIfOutsideBlock()) {
				hold = false;
				return;
			}
			rectTransform.position = mousePos;
		}
	}

	void OnTriggerStay2D(Collider2D col) {
		if (col.gameObject.tag == "Objective") {
			if ((!hold) && (grabbable)) {
				if (toDo != null) {
					toDo(col.gameObject.GetComponent<RequirementItem>().resourceRequirement);
					col.gameObject.GetComponent<BoxCollider2D>().enabled = false;
					transform.position = col.transform.position;
				}
			}
		}
	}

	public void LockInPlace() {
		grabbable = false;
	}
}
