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

#if USING_MRTK2
using Microsoft.MixedReality.Toolkit.Utilities.Solvers;
#endif
namespace SimplifyXR
{

    public class ManualPlacementMRTK2TapToPlace : MonoBehaviour, IPlacementBehavior
    {
        public UnityEvent placementStartedEvent = new UnityEvent();
        public UnityEvent placementEndedEvent = new UnityEvent();
      
        public UnityEvent placementStarted { get => placementStartedEvent; set => placementStartedEvent = value; }
        public UnityEvent placementEnded { get => placementEndedEvent; set => placementEndedEvent = value; }

#if USING_MRTK2
        private TapToPlace tapToPlace;
        private SolverHandler solver;
        void Awake()
        {
            //add tap to place 
            tapToPlace = gameObject.GetOrAddNewComponent<TapToPlace>();

            //use hand/controller as default, may want this to be configurable
            solver = gameObject.GetComponent<SolverHandler>();
            solver.TrackedTargetType = Microsoft.MixedReality.Toolkit.Utilities.TrackedObjectType.ControllerRay;

            tapToPlace.KeepOrientationVertical = true;

            tapToPlace.OnPlacingStarted.AddListener(() => placementStarted.Invoke());
            tapToPlace.OnPlacingStopped.AddListener(() => placementEnded.Invoke());
        }
        void OnDestroy()
        {
            if (tapToPlace)
            {
                tapToPlace.OnPlacingStarted.RemoveAllListeners();
                tapToPlace.OnPlacingStopped.RemoveAllListeners();
                Destroy(tapToPlace);
            }
            if (solver) Destroy(solver);
        }
#endif

        public void StartPlacement()
        {
#if USING_MRTK2
            tapToPlace.StartPlacement();
#endif
        }

        public void StopPlacement()
        {
#if USING_MRTK2
            tapToPlace.StopPlacement();
#endif
        }

        public void EnablePlacement(bool enable)
        {
#if USING_MRTK2
            tapToPlace.enabled = enable;
#endif
        }
    }
}
