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

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

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

	private Vector2 mousePos;
	public Vector3 offset;

	public AudioClip[] clipsSelected;
	public AudioClip[] clipsOrdered;

	public Animator anims;

	private void Start()
	{
		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)
		{
			
		}
	}

	public void OnPointerExit(PointerEventData eventData)
	{
		if (grabbable)
		{
		}
	}

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

	public void OnPointerUp(PointerEventData eventData)
	{
		if (grabbable)
		{
			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 == "JobSite")
		{
			if ((!hold) && (grabbable))
			{
				PlaySoundOrdered();
				grabbable = false;
				JobSite data = col.gameObject.GetComponent<JobSite>();
				transform.position = data.laneKangarooTransform.position+offset;
				MoveKangaroos kangarooMove = GetComponent<MoveKangaroos>();
				kangarooMove.parent = data.parentNewKangaroo;
				kangarooMove.greatgranparent = data.greatgranparentNewKangaroo;
				kangarooMove.gameManager = data.gameManagerNewKangaroo;
				kangarooMove.resource = data.resource;
				kangarooMove.startLaneMovement();
				anims.SetTrigger("Jumping");
			}
		}
	}

	public void LockInPlace()
	{
		grabbable = false;
	}

	private void PlaySoundSelected() {
		AudioManager.Instance.Play(clipsSelected[(int)Random.Range(0, clipsSelected.Length)]);
	}

	private void PlaySoundOrdered() {
		AudioManager.Instance.Play(clipsOrdered[(int)Random.Range(0, clipsOrdered.Length)]);
	}
}
