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

public class AnchorTrackableReferenceNode : MonoBehaviour
{
    /// <summary>
    /// UUID of the node or trackable
    /// </summary>
    public string _ARFNodeUUID;
    /// <summary>
    /// Validity in milliseconds for a subscription to the WA
    /// </summary>
    public int _ValiditySubscription = 100000;

    [SerializeField]
    private List<GameObject> objectsToDeactivate;

    // Start is called before the first frame update
    IEnumerator Start()
    {
        foreach (Transform child in transform)
        {
            child.gameObject.SetActive(false);
        }

        yield return new WaitForSeconds(5.0f);
        // wait for initialization : not perfect way
        int validity = _ValiditySubscription;
        System.Guid subscriptionUUID;
        Debug.Log("UUID to subscribe : " +  _ARFNodeUUID); 

        WorldAnalysisInterface.Instance.SubscribeToPose(null, new System.Guid(_ARFNodeUUID) , ETSI.ARF.OpenAPI.WorldAnalysis.Mode_WorldAnalysis.DEVICE_TO_TRACKABLES, PoseCallback, ref validity, out subscriptionUUID); //TODO : find a value for the token parameter.
    }


    /// <summary>
    /// The callback function used in the susbscription method. It instantiate a prefab or update its pose based on the current situation.
    /// </summary>
    /// <param name="result"></param> 
    /// <param name="pose"> The pose to update in the SM</param>
    public void PoseCallback(WorldAnalysisInterface.PoseEstimationResult result, ETSI.ARF.OpenAPI.WorldAnalysis.Pose pose)
    {
        foreach (Transform child in transform)
        {
            if (!objectsToDeactivate.Contains(child.gameObject))
            {
                child.gameObject.SetActive(true);
            }
        }

        if (pose.Value.Type == ETSI.ARF.OpenAPI.WorldAnalysis.PoseValueType.VECTOR_QUATERNION)
        {
            ETSI.ARF.OpenAPI.WorldAnalysis.VectorQuaternionPoseValue value = (ETSI.ARF.OpenAPI.WorldAnalysis.VectorQuaternionPoseValue)pose.Value;
            transform.position = WorldAnalysisUnityHelper.ConvertETSIVector3ToUnity(value.Position);
            transform.rotation = WorldAnalysisUnityHelper.ConvertETSIARFQuaternionToUnity(value.Rotation);
        }
        else
        {
            Debug.LogWarning("Pose value type not supported yet :" + pose.Value.Type); // Todo : manage other types
        }
    }
}
