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

public class ParallaxSpawner : MonoBehaviour
{

	[SerializeField]
	private float xoffset = 10;

	[System.Serializable]
	private struct ParallaxLayer {
		public float zOverride;
		public float speed;
		public GameObject[] objectPool;

		public float spawnChance;
		public float spawnDelay;
		public float spawnChanceIncreaseDuration;

		public float spawnDelayVariance;

		float cooldown;

		public void resetCooldown() {
			cooldown = spawnDelay;
		}

		public void Spawn(Transform parent, float parallaxOffset, float xoffset) {
			if(objectPool.Length<=0)
				return;
			
			cooldown += Time.deltaTime * ParallaxScroller.SPEED_FACTOR;
			if (parallaxOffset > 0) {
				cooldown += parallaxOffset;
			}
			if (cooldown < spawnDelay) return;

			float chance = spawnChance + Mathf.Max(0f, (cooldown - spawnDelay) / (spawnChanceIncreaseDuration - spawnDelay));

			if (Random.value > chance) return;

			var obj = Instantiate(objectPool[Random.Range(0, objectPool.Length)], parent);
			var scroller = obj.GetComponent<ParallaxScroller>();
			if(scroller==null)
				scroller = obj.AddComponent<ParallaxScroller>();
			
			scroller.speed = -speed;

			float camHalfWidth = Camera.main.orthographicSize * Screen.width / (float)Screen.height;
			float camXPos = Camera.main.transform.position.x;
			
			float x = camXPos+camHalfWidth+scroller.calcWidth()/1.9f;
			obj.transform.position = new Vector3(x, obj.transform.position.y, zOverride);
			cooldown = Random.Range(-spawnDelayVariance, spawnDelayVariance);
		}
	}

	private Player player;

	private void OnEnable() {
		player = FindObjectOfType<Player>();

		for(int i=0; i<layers.Length; i++)
			layers[i].resetCooldown();
	}

	[SerializeField] private ParallaxLayer[] layers;
	private void Update() {
		if(Time.timeScale<=0.00001f)
			return;

		float poff = player == null ? 0 : player.parallaxOffset;
		for( int i = 0; i < layers.Length; ++i ) {
			layers[i].Spawn(transform, poff, xoffset);
		}
	}
}
