using System.Collections;
using System.Collections.Generic;
using Codex.Input;
using Codex.Variables;
using UnityEngine;

public class ClownManager : MonoBehaviour
{
    [SerializeField] private List<Transform> clownPrefabs;
    [SerializeField] private Transform clownContainer;
    [SerializeField] private InputReaderSO inputReader;
    [SerializeField] private BoolVariableSO isPlaying;
    
    private Transform currentClown = null;
    private Rigidbody2D currentClownRigidbody;
    private readonly Vector2 clownInitialPosition = new Vector2(0f, 4f);
    private float clownSpeed = 8.0f;
    private readonly float clownSpeedIncreaseAmount = 0.5f;
    private int clownDirection = 1;
    private readonly float xLimit = 5;
    private bool clownReleased = false;
    private readonly float timeBetweenClowns = 0.5f;
    
    private void OnEnable()
    {
        inputReader.Button1PressedEvent += InputReader_OnButton1;
    }

    private void OnDisable()
    {
        inputReader.Button1PressedEvent -= InputReader_OnButton1;
    }
    
    private void Start()
    {
        SpawnNewClown(); // On Game start
    }

    private void Update()
    {
        if (!isPlaying.Value)
        {
            return;
        }

        if (currentClown)
        {
            var moveAmount = clownSpeed * Time.deltaTime * clownDirection;
            currentClown.position += new Vector3(moveAmount, 0f, 0f);
            if (Mathf.Abs(currentClown.position.x) > xLimit)
            {
                currentClown.position = new Vector3(clownDirection * xLimit, currentClown.position.y, currentClown.position.z);
                clownDirection *= -1;
            }

            if (clownReleased)
            {
                currentClown = null;
                currentClownRigidbody.simulated = true;
                StartCoroutine(DelayedSpawn());
            }
        }
    }
    
    private IEnumerator DelayedSpawn()
    {
        yield return new WaitForSeconds(timeBetweenClowns);
        SpawnNewClown();
        clownReleased = false;
    }

    private void SpawnNewClown()
    {
        var clownPrefab = clownPrefabs[Random.Range(0, clownPrefabs.Count)];
        currentClown = Instantiate(clownPrefab, clownContainer);
        currentClown.position = clownInitialPosition;
        currentClownRigidbody = currentClown.GetComponent<Rigidbody2D>();

        clownSpeed += clownSpeedIncreaseAmount;
    }
    
    private void InputReader_OnButton1()
    {
        clownReleased = true;
    }
}
