using System;
using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks;
using Darkmatter.Core.Contracts.Features.DrawingCatalog;
using Darkmatter.Core.Contracts.Features.Progression;
using Darkmatter.Core.Data.Signals.Features.Drawing;
using Darkmatter.Libs.Observer;
using ZLinq;

namespace Darkmatter.Features.DrawingCatalog.Systems;

public sealed class DrawingCatalogController : IDrawingCatalogController
{
    private readonly IDrawingTemplateCatalog _catalog;
    private readonly IEventBus _bus;
    private readonly IProgressionSystem _progression;

    private readonly List<string> _visible = new();
    public IReadOnlyList<string> VisibleIds => _visible;
    public event Action ListChanged;

    public DrawingCatalogController(
        IDrawingTemplateCatalog catalog,
        IProgressionSystem progression,
        IEventBus bus)
    {
        _catalog = catalog;
        _progression = progression;
        _bus = bus;
    }

    public async UniTask InitializeAsync(CancellationToken ct)
    {
        await _catalog.FetchAsync();
        Refresh();
    }

    public void OnTemplateSelected(string id)
    {
        _bus.Publish(new DrawingSelectedSignal(id));
    }

    private void Refresh()
    {
        _visible.Clear();
        var all = _catalog.AllTemplateIds;
        foreach (var id in all)
            if (!_progression.CompletedTemplateIds.AsValueEnumerable().Contains(id))
                _visible.Add(id);
        foreach (var id in all)
            if (_progression.CompletedTemplateIds.AsValueEnumerable().Contains(id))
                _visible.Add(id);
        ListChanged?.Invoke();
    }
}