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

public class WaveBarHandler : MonoBehaviour , IEventHandler
{
	Image imageRenderer;
	Material _material;

	[Range( 0, 1.0f )] public float percentComplete = 0.5f;

	const float intervalSize = 1f / 6f;
	const float range = 1f - intervalSize;

	void Start()
	{
		EventBroadcaster.registerHandler<PlayerCharging>(this);

		imageRenderer = GetComponent<Image>();

		if ( ! imageRenderer )
		{
			Debug.LogWarning("Failed to Find Image");
			return;
		}

		if ( ! imageRenderer.material || ! imageRenderer.material.HasProperty("_VisiblePercent") )
		{
			Debug.LogError("Object Does not have Wave Bar material attached");
			return;
		}

		// force overwrite because Fuck Unity
		// This normally accesses a sharedMaterial that all instances would
		// modify - which is bad. Make a copy so we just have our instance.
		imageRenderer.material = new Material(imageRenderer.material);

		// Force to 0
		percentComplete = 1/6f;
	}

    void OnDisable()
    {
        EventBroadcaster.unregsterHandler(this);
    }

    void Update()
	{
		// Set the Angle
		imageRenderer.material.SetFloat(
			"_VisiblePercent",
			percentComplete
		);
	}

	public void handleEvent(IGameEvent evt)
	{
		PlayerCharging myEvent = evt as PlayerCharging;
		// Range is actually 0.2 -> 1.0f kinda weird
		percentComplete = myEvent.charge * range + intervalSize;
	}
}
