using System;
using UnityEngine;

public class Luce : MonoBehaviour
{

		public static int maxRange = 20;
		public static int minRange = 4;
		public static Light luce;
		public static float minEnergy = 0;
		public static float maxEnergy = 150;
		static float maxIntensity = 3f, minIntensity = 0f;
		private float energyTimeConsumption = 0.32f;
		public static bool inTrigger = false;
		public int scrollSpeed;
		private int maxLightRange = Luce.maxRange;
		private int minLightRange = Luce.minRange;
		private bool isClick;
		private static float energy;
		private GameObject wind;
		public static float Energy {
				get{ return energy;}
				set {
						if (value >= minEnergy - 0.1f) {
								energy = value;
						}
						calculateActualIntensity ();
				}
		}
	
		

		void Start ()
		{
				if (GameObject.FindGameObjectWithTag ("Wind"))
						wind = GameObject.FindGameObjectWithTag ("Wind");
		}

		void Update ()
		{
				if (Input.GetButtonDown ("Fire1"))
						isClick = true;	
				if (Input.GetButtonUp ("Fire1"))
						isClick = false;
				if (isClick && !inTrigger)
						Energy -= (energyTimeConsumption * Time.deltaTime * luce.range);
						
				luce.range += (Input.GetAxis ("Mouse ScrollWheel")) * scrollSpeed;	
				if (luce.range <= minLightRange)
						luce.range = minLightRange;
				if (luce.range >= maxLightRange)
						luce.range = maxLightRange;
						
				Collider[] hitColliders = Physics.OverlapSphere (this.transform.position, luce.range);
				int i = 0;
				if (isClick) {
						while (i < hitColliders.Length) {
								if (hitColliders [i].CompareTag ("PlatformTrigger"))
										hitColliders [i].gameObject.GetComponentInParent<MovePlatformOnTrigger> ().MoveMe ();
								i++;
						}
				}
		}

		private static void calculateActualIntensity ()
		{
				
				if (Mathf.Round (Energy) < minEnergy)
						luce.intensity = 0;
				else if (Mathf.Round (Energy) >= maxEnergy)
						luce.intensity = maxIntensity;
				else {
				
				
						luce.intensity = ((float)(Mathf.Round (Energy)) / (float)Mass.maxEnergy 
								* (maxIntensity - minIntensity)) 
								+ minIntensity;
				}
				
		}
		void OnTriggerEnter (Collider other)
		{
				if (other.gameObject.CompareTag ("MovingTrigger")) {
						other.gameObject.GetComponent<RandomMover> ().attivo = true;
						inTrigger = true;
						wind.GetComponentInChildren<Animator> ().SetBool ("isPower", false);
				}
		}
		void OnTriggerExit (Collider other)
		{
				if (other.gameObject.CompareTag ("MovingTrigger")) {
						other.gameObject.GetComponent<RandomMover> ().attivo = false;
						inTrigger = false;
						wind.GetComponentInChildren<Animator> ().SetBool ("isPower", true);
				}
				
	
		}


}


