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

public class ItemCanvas : MonoBehaviour {

	public AudioSource audioSource;
	public Sprite[] itemDisplays;
	public int selectedItem = 0;
	public Image itemHolder;
	public bool itemActivated = true, spinStarted = false;
	public RacerScript myRacer;
	
    // Start is called before the first frame update
    void Start () {
		itemActivated = true;
    }

	void Update () {
		if (!myRacer) {
			KartController[] checkThese = FindObjectsOfType<KartController> ();
			foreach (KartController kart in checkThese) {
				if (kart.photonView && kart.photonView.IsMine) {
					myRacer = kart.GetComponentInParent<RacerScript> ();
					return;
				} else {
					myRacer = kart.GetComponentInParent<RacerScript> ();
				}
			}
			return;
		}
		if (Input.GetKeyDown (KeyCode.O)) {
			ItemPickUp (myRacer);
		}

		itemHolder.enabled = !itemActivated;
	}

	public void ItemPickUp (RacerScript racer) {
		StartCoroutine (CycleItems (racer));
	}

    // Update is called once per frame
	IEnumerator CycleItems (RacerScript racer) {
		Debug.Log (racer.name);
		if (spinStarted) {
			yield break;
		} else {
			spinStarted = true;
		}
		itemActivated = false;
		float t = 0;
		while (t < 10) {
			audioSource.Play ();
			itemHolder.sprite = itemDisplays [0];
			yield return new WaitForSecondsRealtime (0.1f);
			audioSource.Play ();
			itemHolder.sprite = itemDisplays [1];
			yield return new WaitForSecondsRealtime (0.1f);
			audioSource.Play ();
			itemHolder.sprite = itemDisplays [2];
			yield return new WaitForSecondsRealtime (0.1f);
			t++;
		}

		selectedItem = Random.Range (0, 3);
		itemHolder.sprite = itemDisplays [selectedItem];
		racer.SetActiveItem (selectedItem);
		spinStarted = false;
		yield return null;
    }
}
