using System;
using XGame.Framework.Interfaces;
using XGame.Framework.ObjectCollection;

namespace XGame.Framework.Map
{
    /// <summary>
    /// Map实例
    /// </summary>
    public abstract class MapView : IMapView, IDisposable
    {
        public MapContext Context { get; private set; }

        private MapBehaviour _behaviour;
        private IEntityViewModel _viewModel;
        private EntityControllerGroup _ctrlGroup;
        public void Init(MapContext context, MapBehaviour behaviour)
        {
            Context = context;
            _behaviour = behaviour;
            _viewModel = CtreatViewModel(behaviour.Collector);
            _ctrlGroup = new EntityControllerGroup(context, _viewModel);
            AddController(_ctrlGroup);
        }
        
        #region 接口实现
        MapBehaviour IMapView.Behaviour => _behaviour;
        public bool Active { get; private set; }


        void IMapView.Enable(object intent)
        {
            if (Active) return;
            Active = true;
            _behaviour.gameObject.SetActive(true);
            _ctrlGroup.Enable(intent);
        }

        void IMapView.Disable()
        {
            if (!Active) return;
            Active = false;
            _behaviour.gameObject.SetActive(false);
            _ctrlGroup.Disable();
        }

        void IUpdate.Update(int millisecond)
        {
            if (!Active) return;
            _ctrlGroup.Update(millisecond);    
        }

        void ILateUpdate.LateUpdate(int millisecond)
        {
            if (!Active) return;
            _ctrlGroup.LateUpdate(millisecond);
        }
        void IDisposable.Dispose()
        {
            OnDispose();
            _ctrlGroup.Dispose();
            _behaviour = null;
            (Context as IDisposable)?.Dispose();
            Context = null;
            _viewModel = null;
        }
        #endregion

        protected abstract IEntityViewModel CtreatViewModel(IObjectCollector collector);
        protected abstract void AddController(IEntityControllerGroup ctrlGroup);

        protected abstract void OnDispose();
    }
}