using System;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;

namespace Plugins.JNGame.Sync.Frame.game
{
    
    //所有帧同步组件的基类
    public abstract class JNSyncFrameComponent<T> : IJNSyncFrameComponent
    {

        //当前输入
        private T _input;
        public T NInput
        {
            get
            {
                if (this._input == null)
                    this._input = Activator.CreateInstance<T>();
                return this._input;
            }
        }
        
        //是否有输入
        public override bool IsInput()
        {
            return this._input != null;
        }

        //是否初始化完成
        [HideInInspector]
        public Boolean isSyncInitSuccess = false;

        //清空输入
        public override void ClearInput(){
            this._input = default(T);
        }
        
        private void Awake()
        {
            //向帧同步获取Id
            this._nId = this.GetSync().nSyncID();
            GetSync().AddSyncActor(this);
            this.OnSyncLoad();
        }

        //初始化完成
        public void OnSyncInitSuccess(){}

        //加载
        public abstract void OnSyncLoad();
        
        //解析
        public T Decoder(byte[] bytes)
        {
            return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes));
        }
        
        //编码
        public byte[] Encoder(T input){
            return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(input));
        }

        public override byte[] Encoder()
        {
            return this.Encoder(this.NInput);
        }

        //帧同步
        public abstract void OnLateSyncUpdate(int dt,JNFrameInfo frame,T input);
        public abstract void OnSyncUpdate(int dt,JNFrameInfo frame,T input);

        public override Task OnSyncUpdateThread(int dt, JNFrameInfo frame)
        {
            return null;
        }
    }
}