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

public class ObjectHurler : MonoBehaviour {

	public GameObject[] singleObjects;
	public GameObject[] asteroidObjects;
	public int maxAsteroidObjects;
	public int minAsteroidObjects;
	public float minAsteroidCooldown = 15;
	public float maxAsteroidCooldown = 25;
	public float minPlanetCooldown = 15;
	public float maxPlanetCooldown = 25;
	private float nextAsteroidTime;
	private float nextPlanetTime;
	void Start () {
		nextAsteroidTime = Time.time + 30f;
		nextPlanetTime = Time.time + 5f;
	}
	
	// Update is called once per frame
	void Update () {
		if(nextAsteroidTime < Time.time){
			nextAsteroidTime = Time.time + Random.Range(minAsteroidCooldown, maxAsteroidCooldown);
			ThrowAsteroidTantrum();
		}
		if(nextPlanetTime < Time.time){
			nextPlanetTime = Time.time + Random.Range(minPlanetCooldown, maxPlanetCooldown);
			ThrowSingle();
		}
	}
	Vector3 spawnPosition;
	void ThrowAsteroidTantrum(){
		setRandomSpawn();
		Vector3 vel = ((CentreOfWorld() - spawnPosition) + randomVector(-1f, 1f, 0.4f)).normalized * 0.1f;
		int asteroidSize = Random.Range(minAsteroidObjects, maxAsteroidObjects);
		for (int i = 0; i < asteroidSize; i++)
		{
			GameObject temp = Instantiate(asteroidObjects[Random.Range(0, asteroidObjects.Length)], spawnPosition + randomVector(-0.5f, 0.5f), Quaternion.identity);
			Rigidbody tempRigid = temp.GetComponent<Rigidbody>();
			tempRigid.velocity = vel + randomVector(-0.002f, 0.002f);
		}
		
	}
	void ThrowSingle(){
		setRandomSpawn();
		GameObject temp = Instantiate(singleObjects[Random.Range(0, singleObjects.Length)], spawnPosition, Quaternion.identity);
		Rigidbody tempRigid = temp.GetComponent<Rigidbody>();
		tempRigid.velocity = ((CentreOfWorld() - temp.transform.position) + randomVector(-3f, 3f, 0.8f)).normalized * 0.1f;
	}
	Vector3 randomVector(float min, float max, float gap){
		return new Vector3(
			randomNumberWithMiddleGap(min, max, gap),
			randomNumberWithMiddleGap(min, max, gap),
			randomNumberWithMiddleGap(min, max, gap)
		);
	}
	Vector3 randomVector(float min, float max){
		return new Vector3(
			Random.Range(min,max),
			Random.Range(min,max),
			Random.Range(min,max)
		);
	}
	float randomNumberWithMiddleGap(float min, float max, float gap){
		if(Random.Range(0, 2) == 1){
			return Random.Range(min, max - gap);
		}else{
			return Random.Range(min + gap, max);
		}
	}
	static Vector3 cacheCentre;
	public static Vector3 CentreOfWorld(){
		
		cacheCentre = Vector3.zero;
		int numberOfThigns = 0;
		for (int i = 0; i < OrbitObject.thingsToOrbit.Length; i++)
		{
			cacheCentre += OrbitObject.thingsToOrbit[i].Position();
			numberOfThigns++;
		}
		cacheCentre = cacheCentre / numberOfThigns;
		return cacheCentre;
	}
	void setRandomSpawn(){
		spawnPosition = randomVector(-6f, 6f, 4f);
	}
}
