using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
namespace AdamSync
{
    public class SyncPlayerTransform : AsyncObjectBase
    {
        private string latestData = "";

        private void OnInit()
        {
            SyncCreateRoom.playerInfoRequset += ReceivePlayInfo;
            if (isPlayer)
            {
                //StartCoroutine(SendMsg());
            }
            else
            {
                //string msg = string.Format("send2room online," + GlobeFlag.userID + "," + GlobeFlag.userName + "," + GlobeFlag.roomID);
                //_ = SyncCreateRoom.SendMessageAsync(msg);
            }
        }

        

        private IEnumerator SendMsg()
        {
            while (true)
            {
                yield return new WaitForSeconds(0.01f);

                var nowData = GetSyncData();
                if (!nowData.Equals(latestData))
                {
                    latestData = nowData;

                    _ = SyncCreateRoom.SendMessageAsync(string.Format("player {0}", nowData));
                }
            }
        }

        public void ReceivePlayInfo(ulong id, string pos, string angle)
        {
            if (id.Equals(userID))
            {
                transform.position = Trans(pos);
                transform.eulerAngles = Trans(angle);
            }
        }

        private Vector3 Trans(string msg)
        {
            string[] data = msg.Split(',');
            Vector3 temp = new Vector3(float.Parse(data[0]), float.Parse(data[1]), float.Parse(data[2]));
            return temp;
        }
        //private void OnDisable()
        //{
        //    Debug.Log("OnDisable");
        //    StopAllCoroutines();
        //    SyncCreateRoom.playerInfoRequset -= ReceivePlayInfo;
        //}
    }
}