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

public class LoraxCuller : MonoBehaviour {
    public Lorax[] Loraces;
    public Transform ChunkKeepAliveTransformsParent;

    private List<Transform> ChunkKeepAliveTransforms = new List<Transform>();
    private List<GameObject>[] EnabledChunks;

    private void Awake() {
        EnabledChunks = new List<GameObject>[Loraces.Length];
        foreach (Transform Child in ChunkKeepAliveTransformsParent) {
            ChunkKeepAliveTransforms.Add(Child);
        }
        for (int LoraxIndex = 0; LoraxIndex < Loraces.Length; LoraxIndex++) {
            EnabledChunks[LoraxIndex] = new List<GameObject>();
            for (int ChunkIndex = 0; ChunkIndex < ChunkKeepAliveTransforms.Count; ChunkIndex++) {
                EnabledChunks[LoraxIndex].Add(null);
            }
        }
    }

    private void Update() {
        Hashtable Refs = new Hashtable();
        for (int LoraxIndex = 0; LoraxIndex < Loraces.Length; LoraxIndex++) {
            Lorax Lorax = Loraces[LoraxIndex];
            for (int ChunkIndex = 0; ChunkIndex < ChunkKeepAliveTransforms.Count; ChunkIndex++) {
                Vector3 KeepAlivePosition = ChunkKeepAliveTransforms[ChunkIndex].position;
                GameObject NewChunk = Lorax.GetChunkAt(KeepAlivePosition.x, KeepAlivePosition.z);
                GameObject OldChunk = EnabledChunks[LoraxIndex][ChunkIndex];
                NewChunk.SetActive(true);

                if (Refs.ContainsKey(NewChunk)) {
                    Refs[NewChunk] = (int)Refs[NewChunk] + 1;
                } else {
                    Refs[NewChunk] = 1;
                }
                if (NewChunk != OldChunk && OldChunk != null) {
                    // No longer pointing to OldChunk, remove ref
                    if (Refs.ContainsKey(OldChunk)) {
                        Refs[OldChunk] = (int)Refs[OldChunk] - 1;
                    } else {
                        Refs[OldChunk] = -1;
                    }
                }

                EnabledChunks[LoraxIndex][ChunkIndex] = NewChunk;
            }
        }

        foreach (GameObject Key in Refs.Keys) {
            if ((int)Refs[Key] < 0) {
                Key.SetActive(false);
            }
        }
    }
}
