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

public class ClothSpawnManager : MonoBehaviour
{
    public GameObject m_ClothPrefab;
    public Collider2D m_SpawnBox;
    public GameObject m_Player;

    public float m_SpawnInterval = 5;
    public float m_SpawnTimer;
    public float m_RandomInterval = 2;

    public int m_ClothPerSpawn = 2;
    public int m_ClothSpawnRandomCountAdd = 1;

    private void Awake()
    {
        
    }
    
    void Start()
    {
        
    }
    
    void Update()
    {
        if (m_Player != null)
        {
            transform.position = m_Player.transform.position;
        }
        IncrementSpawnTimer();
    }

    public void IncrementSpawnTimer()
    {
        if (m_SpawnTimer > 0)
        {
            m_SpawnTimer -= Time.deltaTime;
        }
        else
        {
            int num = m_ClothPerSpawn + Random.Range(-m_ClothSpawnRandomCountAdd, m_ClothSpawnRandomCountAdd+1);
            SpawnClothInBox(num);
            m_SpawnTimer = m_SpawnInterval - Random.Range(-m_RandomInterval, m_RandomInterval);
        }
    }

    [ContextMenu ("Spawn")]
    public void Spawn()
    {
        SpawnClothInBox(3);
    }


    public void SpawnClothInBox(int count)
    {
        int multiplier = 3;
        int totalNum = count * multiplier;
        float spacing = (m_SpawnBox.bounds.extents.x*2) / totalNum;
        List<Vector3> posList = new List<Vector3>();
        Vector3 boxMin = m_SpawnBox.bounds.center - new Vector3(m_SpawnBox.bounds.extents.x, 0, 0);
        
        for (int i = 0; i < totalNum; ++i)
        {
            posList.Add(new Vector3(spacing*i, Random.Range(-m_SpawnBox.bounds.extents.y, m_SpawnBox.bounds.extents.y), 0));
        }

        for (int i = 0; i < count; ++i)
        {
            Vector3 pos = posList[Random.Range((i * 3)+1, (i * 3 + multiplier))];
            SpawnCloth(boxMin + pos);
        }
    }

    public void SpawnCloth(Vector3 _pos)
    {
        GameObject cloth = Instantiate(m_ClothPrefab);
        cloth.transform.position = _pos;
        GrabbableCloth clothScript = cloth.GetComponent<GrabbableCloth>();
        clothScript.m_TimePassed = Random.Range(0, GrabbableCloth.m_MaxTime);
    }
}
