using UnityEngine;
using System;
using System.Collections;

public class ElementPicker : MonoBehaviour {
    public Action<int> OnPick;

    private float Delay = 0.1f; // Animation delay
    private float Duration = 6.0f; // Length of the animation
    private int Amount = 4; // Amount of choices

    private bool canPick = true;

    private int pickedIndex = -1;
    private GameObject basePicker;

    private void Awake() {
        basePicker = GameObject.Find("r_PickerBase");
    }

    /// <summary>
    /// Method that picks and animates towards a new index
    /// </summary>
    public void Pick() {
        // Return if the picker is already animating
        if (!canPick) {
            return; }

        StartCoroutine(PlayPickerSound());

        // Pick a new quarter
        pickedIndex = UnityEngine.Random.Range(0, Amount);

        // Animate the rotation in a nice fashion
        LeanTween.rotateLocal(gameObject, Vector3.up * (360 * 6 + pickedIndex * (360/Amount)), Duration).setEase(LeanTweenType.easeOutCubic).setOnComplete(OnPicked).setDelay(Delay);

        // Disable the pick feature until the animation is done
        canPick = false;
    }

    // Temporary
    private void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            canPick = true;
            Pick();
        }
    }

    private void OnPickComplete() {
        if (OnPick != null) {
            OnPick(pickedIndex);
        }
    }

    /// <summary>
    /// Method that gets called when the animation has picked a new index
    /// </summary>
    private void OnPicked() {
        //transform.localRotation = Quaternion.Euler(0, 0, pickedIndex * 90);
        StopAllCoroutines();
        AudioManager.Instance.Play("crowd_ohh", 1f, false);
        LeanTween.scale(basePicker, Vector3.one * 1.1f, 0.5f).setEase(LeanTweenType.easeInElastic).setOnComplete(delegate() { LeanTween.scale(basePicker, Vector3.one, 1.0f).setEase(LeanTweenType.easeOutCirc); });
        Invoke("OnPickComplete",2.0f);
    }

    private IEnumerator PlayPickerSound() {
        float i = 0;

        while (Duration >= 0) {
            AudioClip clip = AudioManager.Instance.Play("PickerSound", 1f, false);
            yield return new WaitForSeconds((clip.length - 0.20f) + i);
            i += 0.15f;
        }
    }
}