using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
using System.Collections.Generic;

public class MultiImageSpawner : MonoBehaviour
{
  public GameObject[] prefabsToSpawn;

  public Vector3[] spawnOffsets = {
    new Vector3(-0.15f, 0.05f, 0f),
    new Vector3( 0.15f, 0.05f, 0f)
  };

  public Quaternion[] spawnRotation = {
    Quaternion.identity,
    Quaternion.identity
  };

  private ARTrackedImageManager manager;
  private List<GameObject> spawnedObjects = new List<GameObject>();
  private Transform imageTransform;

  void Awake() { manager = GetComponent<ARTrackedImageManager>(); }
  void OnEnable() { manager.trackedImagesChanged += OnImageChanged; }
  void OnDisable() { manager.trackedImagesChanged -= OnImageChanged; }

  void Update()
  {
    if (imageTransform == null) return;
    for (int i = 0; i < spawnedObjects.Count; i++)
      if (spawnedObjects[i] != null)
      {
        spawnedObjects[i].transform.position =
            imageTransform.TransformPoint(spawnOffsets[i]);
        spawnedObjects[i].transform.rotation = spawnRotation[i];
      }
  }

  void OnImageChanged(ARTrackedImagesChangedEventArgs args)
  {
    foreach (var image in args.added)
    {
      imageTransform = image.transform;
      if (spawnedObjects.Count == 0)
        for (int i = 0; i < prefabsToSpawn.Length; i++)
        {
          Vector3 pos = image.transform.TransformPoint(spawnOffsets[i]);
          GameObject obj = Instantiate(prefabsToSpawn[i], pos, spawnRotation[i]);
          //obj.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
          spawnedObjects.Add(obj);
        }
    }
    foreach (var image in args.updated) { imageTransform = image.transform; }
  }
}
