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

public class SpawnObjects : MonoBehaviour {

	public GameObject objectToCollect;
	public GameObject objectToAvoid;
	public GameObject gameOverPopup;

	private GameObject lifeLeft;
	private GameObject currentScore;
	private GameObject[] objects = new GameObject[5];
	private int speed;
	private float spawnRate;

	// Use this for initialization
	private void Start () {
		Time.timeScale = 1f;
		speed = -5;
		spawnRate = Random.Range(1f,2f);
		lifeLeft = GameObject.Find("LifeTextObject");
		currentScore = GameObject.Find("ScoreTextObject");
		InvokeRepeating("InfinitSpawning", 0, spawnRate);
	}

	private void Update(){
		if (Input.GetKeyDown(KeyCode.Escape))
			Application.Quit();

		IncreaseSpeed();
		TriggerGameOver();
	}

	private void TriggerGameOver(){
		string[] life = lifeLeft.GetComponent<Text>().text.Split(':');
		if( life[1].Trim() == "-1") {
			Time.timeScale = 0;
			gameOverPopup.SetActive(true);
		}
	}

	private void IncreaseSpeed(){
		string[] score = currentScore.GetComponent<Text>().text.Split(':');

		if( int.Parse(score[1].Trim()) >= 5 )
			Time.timeScale = 1.5f;
		if( int.Parse(score[1].Trim()) >= 10 )
			Time.timeScale = 2f;
		if( int.Parse(score[1].Trim()) >= 15 )
			Time.timeScale = 2.5f;
		if( int.Parse(score[1].Trim()) >= 20 )
			Time.timeScale = 3f;
		if( int.Parse(score[1].Trim()) >= 25 )
			Time.timeScale = 3.5f;
		if( int.Parse(score[1].Trim()) >= 30 )
			Time.timeScale = 4f;
	}

	private void InfinitSpawning(){
		SpawnObject(objects);
	}

	private void SpawnObject(GameObject[] objects){
		Vector2 velocity  = new Vector2();
		velocity.y = speed;
		
		for(int i = 0; i < objects.Length; i++){
			int rollDice = Random.Range(0,10);

			if(rollDice > 2)
				objects[i] = GameObject.Instantiate(objectToCollect) as GameObject;
			else
				objects[i] = GameObject.Instantiate(objectToAvoid) as GameObject;
			
			if(i == 0)
				objects[i].transform.position = new Vector2(Random.Range(-8,-4), Random.Range(7f,15f));
			if(i == 1)
				objects[i].transform.position = new Vector2(Random.Range(-4,-1), Random.Range(7f,15f));
			if(i == 2)
				objects[i].transform.position = new Vector2(Random.Range(-1,2), Random.Range(7f,15f));
			if(i == 3)
				objects[i].transform.position = new Vector2(Random.Range(2,5), Random.Range(7f,15f));
			if(i == 4)
				objects[i].transform.position = new Vector2(Random.Range(5,8), Random.Range(7f,15f));
			
			objects[i].GetComponent<Rigidbody2D>().velocity = velocity;
		}
	}
}
