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

public class Spawner : MonoBehaviour {

	public Transform SpawnPrefab;
	public float SpawnDelay = 1.0f;
	public float EnergyCost;
	public float EnergyIncomePerSec;
	public float EnergyStartingPool;

	public bool ParentToSpawner=false;
	public float TooClose;
	public float TooFar;

	private float energyPool;
	private float lastSpawnTime;
	private Transform player;
	private GameController gc;

	// Use this for initialization
	void Start () {
		GameObject go = GameObject.Find ("GameController");
		gc = go.GetComponent<GameController>();

		GameObject pgo = GameObject.Find("Player");
		player = pgo.transform;

		energyPool = EnergyStartingPool;
		lastSpawnTime = Time.fixedTime - (float)(gc.rand.NextDouble()) * SpawnDelay;
	}
	
	void FixedUpdate () {
		energyPool += Time.fixedDeltaTime*EnergyIncomePerSec;

		if(Time.fixedTime - lastSpawnTime > SpawnDelay)
		{
			if(energyPool >= EnergyCost)
			{
				energyPool -= EnergyCost;
				DoSpawn();
			}
		}
	}

	private void DoSpawn()
	{
		lastSpawnTime = Time.fixedTime;

		Transform s = (Transform) GameObject.Instantiate(SpawnPrefab);
		s.position = transform.position;

		if(ParentToSpawner)
			s.parent = transform;
		else
			s.localEulerAngles = transform.localEulerAngles;
	}

	private bool DistanceOK()
	{
		float dist = (player.position-transform.position).magnitude;
		if(dist <= TooClose || (TooFar != 0 && dist >= TooFar))
			return false;

		return true;
	}

}
