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

public class ObstacleSpawner : MonoBehaviour
{
    public List<GameObject> Obstacles;

    public List<GameObject> Clouds;

    public PlayerModel PlayerModel;

    private Transform rocket;

    [Range(0.1f, 3f)]
    public float EveryXSeconds = 2f;
    private float _nextMeteorTime = 0f;
    private float _nextCloudTime = 4f;

    void Awake()
    {
        rocket = FindObjectOfType<RocketScript>().gameObject.transform;
    }

    void Update()
    {
        _nextMeteorTime -= Time.deltaTime;
        if (_nextMeteorTime < 0)
        {
            _nextMeteorTime = EveryXSeconds;

            var offset = 1f;
            var position = new Vector3(Random.Range(rocket.position.x - offset, rocket.position.x + offset), transform.position.y, transform.position.z);

            if (ShouldSpawnMeteor())
                Instantiate(Obstacles[Random.Range(0, Obstacles.Count)], position, transform.rotation);

        }

        _nextCloudTime -= Time.deltaTime;
        if (_nextCloudTime < 0)
        {
            _nextCloudTime = Random.Range(2f, 5f); ;

            var position = new Vector3(Random.Range(-3.0f, 3.1f), transform.position.y - 10f, Random.Range(-5f, 10f));
            Instantiate(Clouds[Random.Range(0, Clouds.Count)]).transform.position = position;
        }
    }

    private bool ShouldSpawnMeteor()
    {
        var result = false;

        int percentage = 40 + (PlayerModel?.Level ?? 1) * 5;
        var fixedPercentage = Mathf.Clamp(percentage, 40, 90);
        result = Random.Range(0, 100) < fixedPercentage;

        return result;
    }
}
