﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.Pun;

public class ItemScript : MonoBehaviourPunCallbacks {

	[HideInInspector]
	public GameObject myOwner;
	[HideInInspector]
	public Image background;
	[HideInInspector]
	public Vector3 lastPos, itemRot;
	[HideInInspector]
	public bool pickedUp = false, isActive = false, stackable = false;
	[HideInInspector]
	public Rigidbody rBody;
	[HideInInspector]
	public PlayerBase playerBase;
    [HideInInspector]
    public int stackNumber;

    SphereCollider sphereCollider;

    Vector3 parabolaPoint1;
    Vector3 parabolaPoint2;
    Vector3 parabolaPoint3;

    // Use this for initialization
    public void Awake () {
		lastPos = transform.position;
		CheckType ();
		rBody = GetComponent<Rigidbody> ();
        sphereCollider = gameObject.GetComponent<SphereCollider>();
    }

    public void EnableSphereCollider() {
        sphereCollider.enabled = true;
    }

	void CheckType () {
		if (gameObject.tag == "Potion")
			itemRot = new Vector3 (-45f, 0f, 0f);
		else
			itemRot = new Vector3 (-130f, 0f, 0f);
	}
	
	// Update is called once per frame
	public void Update () {
		if (!pickedUp)
			AvailableItem ();
	}

    IEnumerator MoveParabola(Vector3 direction) {
        float timeInParabola = 0.75f;
        Vector3 positionStart, positionTop, positionEnd;

        //Debug.Log(direction);

        positionStart = parabolaPoint1 = transform.position;
        positionTop = parabolaPoint3 = transform.position + Vector3.up * 4 + direction * 2;
        positionEnd = parabolaPoint2 = transform.position + direction * 4;


        // lerp from start to top
        for (float t = 0.0f; t < 1.0f; t += Time.unscaledDeltaTime / (timeInParabola / 2)) {
            transform.position = Vector3.Lerp(positionStart, positionTop, t);
            yield return null;
        }

        // lerp from top to end
        for (float t = 0.0f; t < 1.0f; t += Time.unscaledDeltaTime / (timeInParabola / 2)) {
            transform.position = Vector3.Lerp(positionTop, positionEnd, t);
            yield return null;
        }
    }

	public void OnDrawGizmosSelected () {
		if (transform.lossyScale != Vector3.one) {
			if (transform.parent) {
				Transform myParent = transform.parent;
				transform.parent = null;
				transform.localScale = Vector3.one;
				transform.parent = myParent;
			} else {
				transform.localScale = Vector3.one;
			}
		}
	}

    void OnDrawGizmos() {
        Gizmos.color = Color.blue;
        Gizmos.DrawSphere(parabolaPoint1, 0.2f);
        Gizmos.color = Color.red;
        Gizmos.DrawSphere(parabolaPoint2, 0.2f);
        Gizmos.color = Color.green;
        Gizmos.DrawSphere(parabolaPoint3, 0.2f);
    }

	void AvailableItem () {

		// give the wand artificial gravity
		Ray ray = new Ray (transform.position, Vector3.down);
		RaycastHit hit;
		if (Physics.Raycast (ray, out hit)) {
			if (hit.distance > 1f)
				rBody.AddForce (0f, -12f, 0f);
			else
				rBody.velocity = Vector3.zero;
		}

		Debug.DrawRay (transform.position, Vector3.down, Color.red);

		// display the item on the ground so it looks like it's something to be picked up
		if (gameObject.tag == "Potion")
			transform.localScale = Vector3.one;
		else
			transform.localScale = Vector3.one * 2.25f;
		itemRot += new Vector3 (0f, 45f * Time.deltaTime, 0f);
		transform.localEulerAngles = itemRot;
	}

	public void AddForceToItem(float forceMagnitude, Vector3 direction) {
		if (!rBody)
			rBody = GetComponent<Rigidbody> ();

        StartCoroutine(MoveParabola(direction));

    }

    [PunRPC]
    public void DropItem(int ownerID, int itemID, float forceMagnitude, Vector3 direction) {
        if (photonView.ViewID != itemID) {
            return;
        }
        GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
        foreach (GameObject player in players) {
            if (player.GetComponent<PlayerBase>().photonView.Owner.ActorNumber == ownerID) {
                player.GetComponent<PlayerBase>().DropItem(gameObject, forceMagnitude, direction);
                EnableSphereCollider();
            }
        }
    }

    [PunRPC]
    public void DropItemStack(int ownerID, int itemID, float forceMagnitude, Vector3 direction, int stack) {
        if (photonView.ViewID != itemID) {
            return;
        }
        GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
        foreach (GameObject player in players) {
            if (player.GetComponent<PlayerBase>().photonView.Owner.ActorNumber == ownerID) {
                player.GetComponent<PlayerBase>().DropItem(gameObject, forceMagnitude, direction);
                stackNumber = stack;
				if (PhotonNetwork.IsMasterClient && stackNumber == 0) {
					PhotonNetwork.Destroy(photonView);
					return;
				}
                EnableSphereCollider();
                if (gameObject.tag == "Potion") {
                    foreach (GameObject part in gameObject.GetComponent<PotionScript>().potionParts) {
                        part.SetActive(true);
                    }
                }
            }
        }
    }
}
