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

public class PushButton : Switcher {
	
	public List<ActivableObject> Targets;
	public bool AutoStop = true;
	public float AutoStopDuration = 10.0f;
	float TimeSinceLastStop = 0.0f;

	Material CurMat;
	Material GaugeMat;

	int GaugeProp;

	// Use this for initialization
	void Start () {
		MeshRenderer MR = GetComponent<MeshRenderer>();
		CurMat = MR.material;
		GaugeProp = Shader.PropertyToID("_Gauge");
		Transform Gauge = transform.FindChild("Gauge");
		if(Gauge) {
			MeshRenderer MRGauge = Gauge.GetComponent<MeshRenderer>();
			GaugeMat = MRGauge.material;
		}
		SetState(IsOn);
		if(GaugeMat) {
			GaugeMat.SetFloat(GaugeProp,IsOn ? 0.0f : 1.0f);
		}
	}

	void Update() {
		if(AutoStop && IsOn) {
			TimeSinceLastStop += Time.deltaTime;
			float GaugeValue = Mathf.Clamp01(TimeSinceLastStop / AutoStopDuration);
			if(GaugeMat) {
				GaugeMat.SetFloat(GaugeProp,GaugeValue);
			}
			foreach(var Target in Targets) {
				if(Target) Target.SetGauge(this, GaugeValue);
			}
			if(TimeSinceLastStop>AutoStopDuration) {
				SetState(false);
				TimeSinceLastStop = 0.0f;
			}
		}
	}

	public override void SetState(bool NewOn) {
		base.SetState(NewOn);
		if(NewOn) TimeSinceLastStop = 0.0f;
		CurMat.color = IsOn ? Color.green * 10.0f : Color.red;
		foreach(var Target in Targets) {
			if(Target) Target.SetState(this, NewOn);
		}
	}

}
