using System.Collections.ObjectModel;

using Avalonia;

using DynamicData;

using InkForge.Desktop.Models;

using Microsoft.Extensions.DependencyInjection;

namespace InkForge.Desktop.ViewModels.Workspaces
{
	public class WorkspaceViewModel
	{
		private readonly Workspace _workspace;
		private readonly NoteStore _noteStore;
		private readonly ReadOnlyObservableCollection<Node<Note, int>> _notes;

		public string Name => _workspace.Name;

		public ReadOnlyObservableCollection<Node<Note, int>> Notes => _notes;

		public WorkspaceViewModel(Workspace workspace, NoteStore noteStore)
		{
			_workspace = workspace;
			_noteStore = noteStore;
			noteStore.Notes
				.AsObservableChangeSet(m => m.Key)
				.Transform(m => m.Value, true)
				.TransformToTree(m => m.Id)
				.Bind(out _notes).Subscribe();
		}
	}

	public interface IWorkspaceViewModelFactory
	{
		WorkspaceViewModel Create(Workspace workspace);
	}

	namespace Internal
	{
		internal class WorkspaceViewModelFactory : IWorkspaceViewModelFactory
		{
			private static ObjectFactory<WorkspaceViewModel>? s_workspaceViewModelFactory;

			public static WorkspaceViewModel Create(Workspace workspace)
			{
				s_workspaceViewModelFactory ??= ActivatorUtilities.CreateFactory<WorkspaceViewModel>([typeof(Workspace)]);
				return s_workspaceViewModelFactory(workspace.Services, [workspace]);
			}

			WorkspaceViewModel IWorkspaceViewModelFactory.Create(Workspace workspace) => Create(workspace);
		}
	}
}
