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

public class Leak : MonoBehaviour {

	public bool Leaking;
	public LeakHandler leakHandler;
	public TypingHandler typeHandler;
	//public KeyCode keyCode;
	public string Key;
	public KeyCode mainKey;
	public bool SpecialKey;
	public Image visual, timer;
	public Text indicator;
	float timeOut, interval, pluggedValue;
	int timerCoolDown;
	AudioSource leakingSound, plug;
	bool plugging;

	void Awake() {
		typeHandler = FindObjectOfType<TypingHandler>();
		leakingSound = GetComponent<AudioSource>();
		plug = GameObject.Find("Plug").GetComponent<AudioSource>();
	}

	void Start() {
		if (!SpecialKey)
			Key = typeHandler.FindSpareLetter();
		indicator.text = Key;
		CoolDown();
		CheckForLeaks();
		progressTimer();
	}

	public void Init() {
		if (!SpecialKey)
			Key = typeHandler.FindSpareLetter();
		indicator.text = Key;
		pluggedValue = 0;
		timeOut = UnityEngine.Random.Range(5,20); //Randomise Time to Plug Hole. BALANCE.
		interval = 1/timeOut;
		playLeak();
		Leaking = true;
	}

	void progressTimer() {
		if (!Leaking && gameObject.activeInHierarchy && timerCoolDown == 0) {
			timerCoolDown = 5;
			//If fully plugged/repaired
			if (pluggedValue >= 1) {
				gameObject.SetActive(false);
				Leaking = false;
				leakHandler.AddLeak(this);
				leakHandler.NewLeak();
			}
			timer.fillAmount = 1 - pluggedValue;
			pluggedValue += interval;
		}
		Invoke("progressTimer", 0.5f);
	}

	void CoolDown() {
		if (timerCoolDown > 0)
			timerCoolDown--;
		Invoke("CoolDown", 0.1f);
	}

	void Update() {
		
		if (gameObject.activeInHierarchy) {
			KeyCode newInput;
			if (SpecialKey)
				newInput = mainKey;
			else
				newInput = (KeyCode) Enum.Parse(typeof(KeyCode), Key);
			if (Input.GetKey(newInput)) {
				if (!plugging) {
					plugging = true;
					plug.Play();
				}
				stopLeak();
				Leaking = false;
				visual.enabled = false;
				indicator.color = new Color(1,1,1,0.1f);
			} else {
				playLeak();
				plugging = false;
				Leaking = true;
				visual.enabled = true;
				indicator.color = new Color(1,1,1,1);
			}
		} else {
			Leaking = false;
			plugging = false;
		}
	}

	void playLeak() {
		if (!Leaking) {
			leakingSound.Play();
		}
	}

	void stopLeak() {
		if (Leaking) {
			leakingSound.Stop();
		}
	}

	void CheckForLeaks() {
		if (gameObject.activeInHierarchy) {
			if (Leaking) {
				leakHandler.Flood();
			} else {
				leakHandler.DrainWater();
			}
			Invoke("CheckForLeaks",1);
		}
	}
}
