﻿/****************************************************************************
* Copyright 2019 Xreal Techonology Limited. All rights reserved.
*                                                                                                                                                          
* This file is part of NRSDK.                                                                                                          
*                                                                                                                                                           
* https://www.xreal.com/        
* 
*****************************************************************************/

namespace NRKernal.Persistence
{
    using System;
    using UnityEngine;
    using UnityEngine.EventSystems;
    using UnityEngine.UI;
    using Photon.Pun;
    using Photon.Realtime;
    using NRKernal.NRExamples;
    using ExitGames.Client.Photon;

    /// <summary> An anchor item. </summary>
    public class AnchorItem : MonoBehaviourPunCallbacks, IPointerClickHandler
    {
        /// <summary> The key. </summary>
        public string key;
        /// <summary> The on anchor item click. </summary>
        public Action<string, GameObject> OnAnchorItemClick;
        /// <summary> The anchor panel. </summary>
        [SerializeField]
        private GameObject canvas;
        [SerializeField]
        private Text anchorUUID;

        private NRWorldAnchor m_NRWorldAnchor;
        private Material m_Material;

        public Button saveButton;  
        // public PhotonView photonView;

        void Start()
        {
            if (TryGetComponent(out m_NRWorldAnchor))
            {
                if (canvas != null)
                    canvas.SetActive(true);
                if (anchorUUID != null)
                    anchorUUID.text = m_NRWorldAnchor.UUID;
                m_Material = GetComponentInChildren<Renderer>()?.material;
                if (m_Material != null)
                {
                    m_NRWorldAnchor.OnTrackingChanged += (NRWorldAnchor worldAnchor, TrackingState state) =>
                    {
                        switch (state)
                        {
                            case TrackingState.Tracking:
                                //m_Material.color = Color.green;
                                break;
                            case TrackingState.Paused:
                                m_Material.color = Color.white;
                                break;
                            case TrackingState.Stopped:
                                m_Material.color = Color.red;
                                break;
                        }
                    };
                }
            }
        }

        public void Save()
        {
            if (m_NRWorldAnchor != null)
            {
                
                m_NRWorldAnchor.SaveAnchor(success =>
                {
                    if (success)
                    {
                        Debug.Log("Anchor saved successfully!");
                        saveButton.image.color = Color.green;
                    }
                    else
                    {
                        Debug.LogError("Failed to save anchor!");
                        saveButton.image.color = Color.red;
                    }
                });
                
            }
               
        }

        public async void CloudSave()
        {
            if (m_NRWorldAnchor != null)
            {
                bool result=await NRWorldAnchorStore.Instance.CloudSaveAnchor(m_NRWorldAnchor);
                if (result)
                {
                    NRDebugger.Info("Ready to share anchor: " + m_NRWorldAnchor.UUID);
                    Debug.Log("Ready to share anchor: " + m_NRWorldAnchor.UUID);
                    ShareUUID();
                }
                else
                {
                    Debug.LogError("Failed to save anchor");
                }
            }
            else
            {
                Debug.LogError("m_NRWorldAnchor is null, failed to save this anchor to CloudStorage");
            }
        }        

        public void Erase()
        {
            if (m_NRWorldAnchor != null)
                m_NRWorldAnchor.EraseAnchor();
        }

        public void Destory()
        {
            if (m_NRWorldAnchor != null)
                m_NRWorldAnchor.DestroyAnchor();
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            OnAnchorItemClick?.Invoke(key, gameObject);
        }


        public void ShareUUID()
        {
            if (m_NRWorldAnchor != null)
            {
                UUIDManager.instance.ShareAnchorUUID(m_NRWorldAnchor.UUID);
                Debug.Log("Shared anchor: " + m_NRWorldAnchor.UUID);
            }
        }

 		public void ToggleCanvasVisibility()
        {
            // Check if the canvas is currently activated in the hierarchy.
            bool isActive = canvas.activeInHierarchy;

            // Switch the active state of the canvas.
            canvas.SetActive(!isActive);
        }

    }
}
