using UnityEngine;
using System.Collections;

public class CoinScript : MonoBehaviour {
    public int points;
    public GUIText guiText;
    public AudioClip collectSound;

    private float timeCollected;
    private bool isCollected = false;
    private int scoreCollected;
    private Texture2D emptyTexure;

    private const float SPIN_DEGREES_PER_FRAME = 20f;
    private const float SECONDS_COLLECTED_ANIMATION = 0.4f;
    private const float SECONDS_POINTS_COLLECTED = 2f;

	// Use this for initialization
	void Start () {
        GUIScaler.Initialize();
	}

    void OnGUI() {
        if (isCollected) {
            string pointsTxt = "<color=\"#626363\"><size=25>" + scoreCollected + " Points!</size></color>";

            Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
            Vector2 textBox = new Vector2(300, 50);

            GUIScaler.Begin();
            GUI.Label(new Rect(pos.x - textBox.x / 2, pos.y - textBox.y / 2, textBox.x, textBox.y), pointsTxt);
            GUIScaler.End();
        }
    }
	
	// Update is called once per frame
	void Update () {
	
        if (isCollected) {
            transform.Rotate(Vector3.forward * SPIN_DEGREES_PER_FRAME);

            float timeSinceCollected = (Time.time - timeCollected);
            if (timeSinceCollected > SECONDS_POINTS_COLLECTED) {
                Destroy(gameObject);
            }
        }
	}

    public bool getIsCollected() {
        return isCollected;
    }

    public void collected(int score) {
        if (!AudioSingleton.instance.IsSFXMuted()) {
            AudioSource.PlayClipAtPoint(collectSound, transform.position);
        }
        isCollected = true;
        scoreCollected = score;
        timeCollected = Time.time;
        StartCoroutine(FadeTo(0.0f, SECONDS_COLLECTED_ANIMATION));
    }

    IEnumerator FadeTo(float aValue, float aTime)
    {
        float alpha = transform.renderer.material.color.a;
        for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime)
        {
            Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha,aValue,t));
            transform.renderer.material.color = newColor;
            yield return null;
        }
    }
}
