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

public class UiDraggableItem : MonoBehaviour
{

	public GameObject prefab;
	bool isMouse = false;
	bool dragStarted = false;
	GameObject currPrefab;

	public Item currItem;

	Vector3 lastPoint;
	public bool placable;
	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {

		if (isMouse)
		{
			if (Input.GetMouseButton(0))
			{
				if (dragStarted)
				{
					DragPrefab();
				}

			}
			if (Input.GetMouseButtonUp(0) && isMouse)
			{
				ProcessEndOfDrag();
				isMouse = false;
			}
		}
	}

	void InstantiatePrefab()
	{
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		if (Physics.Raycast(ray, out hit, 1000))
		{
			if(hit.transform.gameObject.tag == "Terrain")
			{
				currPrefab = Instantiate(prefab, hit.point, Quaternion.identity);
				SphereCollider c = currPrefab.GetComponent<SphereCollider>();
				if(c!= null)
				{
					c.enabled = false;
				}
			}
		}
	}

	void DragPrefab()
	{
		if(currPrefab != null)
		{
			
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast(ray, out hit, 1000))
			{
				string tag = hit.transform.gameObject.tag;
				if (tag== "Terrain")
				{
					lastPoint = hit.point;
					currPrefab.transform.position = hit.point + new Vector3(0, .7f, 0);
				}
				else if (tag == "Item")
				{
					lastPoint = hit.point;
					currPrefab.transform.position = hit.point + new Vector3(0, .7f, 0);

				}
				
			}
		}
	}

	void ProcessEndOfDrag()
	{
		if (currPrefab != null)
		{
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast(ray, out hit, 1000))
			{
				string tag = hit.transform.gameObject.tag;
				if (tag == "Item")
				{
					InteractableItem i = hit.transform.gameObject.GetComponent<InteractableItem>();
					if(i != null)
					{
						Debug.Log("i not null");
						if (i.CanAcceptItem(currItem))
						{
							i.TakeItem(currItem);
						}
					}
				}

			}





			if (placable)
			{
				currPrefab.transform.position = lastPoint;
				SphereCollider c = currPrefab.GetComponent<SphereCollider>();
				if (c != null)
				{
					c.enabled = true;
				}
			}
			else
			{
				Destroy(currPrefab);
			}

			lastPoint = Vector3.zero;
			//currItem = null;
			currPrefab = null;
			dragStarted = false;
		}
	}

	public void OnMouseDown()
	{
		isMouse = true;
	}

	public void OnMouseExit()
	{
		if(isMouse && Input.GetMouseButton(0))
		{
			dragStarted = true;
			InstantiatePrefab();
		}
	}
}
