using UnityEngine;
using System.Collections;

public class StaffGuide : MonoBehaviour {

    private float brightness = 0f;
    enum GuideState { normal, bright, disabled };
    private GuideState guideState = GuideState.normal;

    private Transform artifactPos;
    private Transform playerPos;

    public float maxDistance = 50f;

    Renderer renderThingy;
    Material material;

    public GameObject crystalLightObject;
    Light crystalLight;

	// Use this for initialization
	void Start () {
        crystalLight = crystalLightObject.GetComponent<Light>();
        renderThingy = GetComponent<Renderer>();
        playerPos = GameObject.FindWithTag("Player").transform;

        EventManager.OnBrightGuideStart += StartBright;
        RoundManager.OnRoundStart += Restart;
        //StartBright(30f);
        Debug.Log("HELLO");
        Artefact.OnUse += DisableGuide;
	}
	
	// Update is called once per frame
	void Update () {
        if(artifactPos == null && guideState != GuideState.disabled)
        {
            artifactPos = GameObject.FindWithTag("Artifact").transform;
        }
        if(guideState == GuideState.normal)
        {
            Normal();
        }
        else if (guideState == GuideState.bright)
        {
            Bright();
        }
        renderThingy.material.SetColor("_EmissionColor", new Color(brightness, brightness, 0f));
        crystalLight.intensity = brightness;
	}

    void Normal()
    {
        Vector3 heading = artifactPos.position - transform.position;
        float distance = heading.magnitude;
        brightness = 1 - (distance / maxDistance);
    }

    void Bright()
    {
        Vector3 heading = artifactPos.position - transform.position;
        float distance = heading.magnitude;
        Vector3 aDir = heading / distance;
        Vector3 pDir = playerPos.forward;
        Vector3 avg = aDir - pDir;
        brightness = 1 - (Mathf.Abs(avg.x) + Mathf.Abs(avg.y) + Mathf.Abs(avg.z)) / 3;
    }

    void StartBright(float time)
    {
        StartCoroutine(BrightCountdown(time));
    }

    IEnumerator BrightCountdown(float time)
    {
        guideState = GuideState.bright;
        yield return new WaitForSeconds(time);
        guideState = GuideState.normal;
    }

    void Restart()
    {
        guideState = GuideState.normal;
        artifactPos = GameObject.FindWithTag("Artifact").transform;
    }

    void DisableGuide()
    {
        guideState = GuideState.disabled;
    }
}
