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

public class BatUser : Switcher {
	
	public List<ActivableObject> Targets;

	Material CurMat;
	List<Socket> Slots;
	public float BateryDuration = 30.0f;
	public float MinimumQuantity = 0.0f;

	// Use this for initialization
	void Start () {
		MeshRenderer MR = GetComponent<MeshRenderer>();
		CurMat = MR.material;
		Socket[] AllSlots = GetComponentsInChildren<Socket>();
		Slots = new List<Socket>();
		foreach(var Slot in AllSlots) {
			Slots.Add(Slot);
		}
		SetState(IsOn);
	}

	void Update() {
		bool NewIsOn = false;
		bool SlotMissing = false;
		foreach(var Slot in Slots) {
			if(Slot && Slot.Slot) {
				Batery Bat = Slot.Slot.GetComponent<Batery>();
				if(Bat) {
					if(Bat.Gauge<=MinimumQuantity) {
					SlotMissing = true;
					}
				} else {
					SlotMissing = true;
				}
			} else {
				SlotMissing = true;
			}
		}

		NewIsOn = !SlotMissing;
		if(!SlotMissing) {
			foreach(var Slot in Slots) {
				if(Slot && Slot.Slot) {
					Batery Bat = Slot.Slot.GetComponent<Batery>();
					if(Bat) {
						Bat.Gauge = Mathf.Clamp01(Bat.Gauge - Time.deltaTime / BateryDuration);
					}
				}
			}
		}

		if(NewIsOn != IsOn) {
			IsOn = NewIsOn;
			SetState(NewIsOn);
		}
	}

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