using System;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

using Random = UnityEngine.Random;


public class GameplayManager : MonoBehaviour
{
	[Serializable]
	public sealed class Building
	{
		public string ID;
		public int MaxSize;
	}
	
	public GameObject GameZone;
	public GameObject GameOverGUI;
	public Building[] Buildings;
	public GameObject BuildingsContainer;
	private BuildingPlaceholder[] _buildingPlaceholders;

	public static bool GameOver = false;

	public void Start()
	{
		GameOver = false;
		_buildingPlaceholders = BuildingsContainer.GetComponentsInChildren<BuildingPlaceholder>();

		foreach (var placeholder in _buildingPlaceholders)
		{
			var i = Random.Range(0, Buildings.Length);
			placeholder.GenerateBuilding(Buildings[i]);
		}
	}
	
	private void Update()
	{
		var centerCam = Camera.main.transform.position;
		var topRightCam = Camera.main.ScreenToWorldPoint(new Vector3(0, 0));
		var bottomLeftCam = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));

		var topRightCorner = GameZone.transform.position
		                     + Vector3.Scale(GameZone.transform.localScale, Vector3.right + Vector3.up)
		                     - (centerCam - topRightCam)
		                     - Vector3.right * 25f;

		var bottomLeftCorner = GameZone.transform.position
		                       + Vector3.Scale(GameZone.transform.localScale, Vector3.left + Vector3.down)
		                       - (centerCam - bottomLeftCam)
		                       - Vector3.left * 25f;

		var pos = Camera.main.transform.position;


		if (Input.mousePosition.x < 100)
		{
			pos.x -= Time.deltaTime * 5;
		}
		
		if (Input.mousePosition.x > Screen.width - 100)
		{
			pos.x += Time.deltaTime * 5;
		}
		
		
		pos.x = Mathf.Clamp(pos.x, bottomLeftCorner.x, topRightCorner.x);
		pos.y = Mathf.Clamp(pos.y, bottomLeftCorner.y, topRightCorner.y);
		
		Camera.main.transform.position = pos;

		var canStillGrowBuildings = false;
		foreach (var placeholder in _buildingPlaceholders)
		{
			if (placeholder != null && placeholder.GrowStep < placeholder.MaxGrowStep)
			{
				canStillGrowBuildings = true;
				break;
			}
		}
		

		if (!canStillGrowBuildings || ScoreManager.Instance.Money < -50000 || ScoreManager.Instance.TimeLeft <= 0)
		{
			GameOver = true;
		}

		if (GameOver)
		{
			GameOverGUI.SetActive(true);
			GameOverGUI.transform.Find("Score").GetComponent<Text>().text = "Score: " + ScoreManager.Instance.Points;
			
			foreach (var placeholder in _buildingPlaceholders)
			{
				if (placeholder != null)
				{
					placeholder.enabled = false;
				}
			}
		}
	}

	public void Retry()
	{
		AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/button_click"), Camera.main.transform.position);
		SceneManager.LoadScene("Game");
	}

	public void Exit()
	{
		AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/button_click"), Camera.main.transform.position);
		Application.Quit();
	}
}
