using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using Unity.Mathematics;
using Unity.VisualScripting;
using UnityEngine;

using Random = UnityEngine.Random;
public class Zone : MonoBehaviour
{
    public float closingSpeed;
    public float sphereScale;
    public float SpawnInterval = 0;
    public GameObject sphere;
    public GameObject enemyPb;
    public Transform sphereSpawnPoint = null;
    public int enemyCount;
    public Transform[] enemySpawnPoints;
    public Transform islandCenter;
    public Renderer[] environmentToFade;
    private GameObject _sphere;
    private int _spawnedEnemies = 0;
    private int _enemiesToSpawn = 0;

    void Start(){
        _enemiesToSpawn = enemyCount;
    }
    void Update(){
        if(_spawnedEnemies == 0 && _enemiesToSpawn == 0){
            _spawnedEnemies = -1;
            StartCoroutine(OpenSphere());
        }
    }
    void OnTriggerEnter(Collider collider){
        if(!collider.transform.CompareTag("Player")) return;
        _sphere = Instantiate(sphere, sphereSpawnPoint.position, Quaternion.identity);
        _sphere.transform.localScale = new Vector3(sphereScale, sphereScale, sphereScale);
        StartCoroutine(CloseSphere());
    }

    private IEnumerator CloseSphere()
    {
        float x = 0;
        while(x < 1){
            x = Mathf.MoveTowards(x, 1, closingSpeed*Time.deltaTime);
            _sphere.GetComponent<Renderer>().material.SetFloat("_Progress", x);
            yield return null;
        }
        StartCoroutine(SpawnEnemies());
    }

    private IEnumerator OpenSphere()
    {
        float x = 1;

        while(x > 0){
            x = Mathf.MoveTowards(x, 0, closingSpeed*Time.deltaTime);
            _sphere.GetComponent<Renderer>().material.SetFloat("_Progress", x);
            for(int i = 0; i < environmentToFade.Length; i++){
                environmentToFade[i].GetPropertyBlock(environmentToFade[i].GetComponent<MaterialPropertyBlock>().propBlock);
            
                environmentToFade[i].GetComponent<MaterialPropertyBlock>().propBlock.SetFloat("_Progress", 1-x);
                environmentToFade[i].SetPropertyBlock(environmentToFade[i].GetComponent<MaterialPropertyBlock>().propBlock);
            }
            yield return null;
        }
        Destroy(_sphere);
        Destroy(gameObject);

    }

    private IEnumerator SpawnEnemies()
    {
        while(_enemiesToSpawn > 0){
            Vector3 spawnPoint = enemySpawnPoints[Random.Range(0, enemySpawnPoints.Length)].position;
            var enemy = Instantiate(enemyPb, spawnPoint, Quaternion.identity);
            enemy.GetComponent<Health>().death.AddListener(delegate{_spawnedEnemies--;});
            enemy.GetComponent<EnemyStateManager>().pointToEnterIsland = islandCenter;
            _spawnedEnemies++;
            _enemiesToSpawn--;
            yield return new WaitForSeconds(SpawnInterval);
        }
    }
}
