using System;
using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks;
using Darkmatter.Core.Contracts.Features.DrawingCatalog;
using Darkmatter.Features.DrawingCatalog.Systems;
using VContainer.Unity;

namespace Darkmatter.Features.DrawingCatalog
{
    public class DrawingCatalogPresenter : IStartable, IDisposable
    {
        private readonly DrawingCatalogView _view;
        private readonly IDrawingCatalogController _controller;
        private readonly IDrawingTemplateCatalog _catalog;
        private readonly CancellationTokenSource _cts = new();

        public DrawingCatalogPresenter(DrawingCatalogView view, DrawingCatalogController controller,
            IDrawingTemplateCatalog catalog)
        {
            _view = view;
            _controller = controller;
            _catalog = catalog;
        }

        public void Start()
        {
            _view.OnItemClicked += OnItemClicked;
            _controller.ListChanged += OnListChanged;
        }

        private void OnItemClicked(string id) =>
            _controller.OnTemplateSelected(id);

        private void OnListChanged() =>
            RefreshAsync(_cts.Token).Forget();

        private async UniTask RefreshAsync(CancellationToken ct)
        {
            var ids = _controller.VisibleIds;
            var vms = new List<CatalogItemVM>(ids.Count);
            foreach (var id in ids)
            {
                if (ct.IsCancellationRequested) return;
                var thumb = await _catalog.GetThumbnailAsync(id);
                vms.Add(new CatalogItemVM(id, thumb));
            }

            if (ct.IsCancellationRequested) return;
            _view.SetItems(vms);
        }

        public void Dispose()
        {
            _view.OnItemClicked -= OnItemClicked;
            _controller.ListChanged -= OnListChanged;
            _cts.Cancel();
            _cts.Dispose();
        }
    }
}