using System;
using XGame.Framework.Quality;
using XGame.Framework.Time;
using XGame.Framework.UI;

namespace XGame.Framework.Map
{
    public sealed class MapContext : IDisposable
    {
        public IQualityModule Quality { get; private set; }

        private ITimeModule _timeModule;
        private ITimeProxy _timeProxy;
        public ITimeProxy Time => _timeProxy ?? (_timeProxy = new TimeProxy(_timeModule));

        public IMapModule Map { get; private set; }
        public IUIModule UI { get; private set; }

        /// <summary>
        /// 资源加载模块，需要时才创建
        /// </summary>
        private IMapAssetModule _assetModule;
        public IMapAssetModule Asset => _assetModule ?? (_assetModule = new MapAssetModule(this));

        public MapContext(IQualityModule quality, ITimeModule time, IMapModule map, IUIModule ui)
        {
            Quality = quality;
            _timeModule = time;
            Map = map;
            UI = ui;
        }

        public MapContext Clone()
        {
            return new MapContext(Quality, _timeModule, Map, UI);
        }
        /// <summary>
        /// 取消定时器、清理资源加载监听等
        /// </summary>
        public void Clear()
        {
            _timeProxy?.CancelAll();
            _assetModule?.StopAllAsyncs();
        }
        void IDisposable.Dispose()
        {
            Quality = null;
            _timeModule = null;
            Map = null;
            _timeProxy?.CancelAll();
            _timeProxy = null;
            (_assetModule as IDisposable)?.Dispose();
            _assetModule = null;
        }
    }

    public interface IMapContextSetter
    {
        MapContext Context { set; }
    }
}