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

public class GameController : MonoBehaviour
{
    public GameObject[] Balls;
    public Vector2 ballValue;
    public int ballCount;
    public float ballWait;
    public float waveWait;

    public Text scoreText;
    private int score = 0;

    public Text gameoverText;
    private bool gameOver;

    private bool restart;
    public Text restartText;

    private IEnumerator BallWaves()
    {
        while (true)
        {
            for (int i = 0; i < ballCount; ++i)
            {
                GameObject Ball = Balls[Random.Range(0, Balls.Length)];
                Vector2 spawnPosition = new Vector2(Random.Range(-ballValue.x, ballValue.x), ballValue.y);
                Quaternion spawnRotion = Quaternion.identity;
                Instantiate(Ball, spawnPosition, spawnRotion);
                yield return new WaitForSeconds(ballWait);
            }
            yield return new WaitForSeconds(waveWait);

            if (gameOver)
            {
                restart = true;
                restartText.text = "Нажмите 'R', чтобы начать игру заново, или 'Q' - для выхода.";
                break;
            }

        }
    }

    private void Start()
    {
        gameOver = false;
        restart = false;
        gameoverText.text = "";
        restartText.text = "";
        UpdateScore();
        StartCoroutine(BallWaves());
    }

    private void Update()
    {
        if (restart)
        {
            if (Input.GetKeyDown(KeyCode.R))
            {
                SceneManager.LoadScene("Main");
            }
            if (Input.GetKeyDown(KeyCode.Q))
            {
                Application.Quit();
            }
        }
    }

    public void UpdateScore()
    {
        scoreText.text = "Score: " + score.ToString();
    }
    
    public void AddScore (int newScoreValue)
    {
        score += newScoreValue;
        UpdateScore();
    }

    public void GameOver()
    {
        gameoverText.text = "GAME OVER!!!";
        gameOver = true;
    }
}
