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

public class TrailMgr : MonoBehaviour
{
    public SpaceshipController controller;
    public TrailRenderer trail;

    public Vector3[] positions;
    public Transform trailPoolParent;
    public GameObject trailColliderObj;
    public List<GameObject> trailsPool;
    
    void Start(){
    }

    // Update is called once per frame
    void Update(){
        #if PLATFORM_ANDROID
        positions = new Vector3[trail.positionCount];
        int length = trail.GetPositions(positions);
        if(length > trailsPool.Count){
            //must create new trails
            int missingCount = length - trailsPool.Count;
            for(int i =0; i < missingCount; i++){
                GameObject newTrail = Instantiate(trailColliderObj, trailPoolParent);
               // Debug.Log("Spawned new trail obj " + newTrail.name);
                newTrail.GetComponent<TrailCollider>().trailMgr = this;
                trailsPool.Add(newTrail);
            }
        }
        for(int i =0; i < trailsPool.Count; i++){
            if(i < length){
                trailsPool[i].SetActive(true);
                trailsPool[i].transform.position = positions[i];
            }else{
                trailsPool[i].SetActive(false);
            }
        }
        #endif
    }



    public void OnColliderHit(Collider2D hit){
        controller.TrailCollided(hit);
    }

    void OnValidate(){
        if(controller==null){
            controller = GetComponent<SpaceshipController>();
        }
    }
}
