using System.Reactive;

using Avalonia.Platform.Storage;

using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;

using Dock.Model.Mvvm.Controls;

using InkForge.Desktop.Managers;
using InkForge.Desktop.Services;

namespace InkForge.Desktop.ViewModels.Documents;

public partial class WelcomePageDocumentViewModel : Document
{
	private readonly WorkspaceManager _workspaceController;

	public WelcomePageDocumentViewModel(WorkspaceManager workspaceController)
	{
		Title = "Welcome";

		_workspaceController = workspaceController;
	}

	[RelayCommand]
	private async Task OnCreateNew()
	{
		var storageProvider = this.GetStorageProvider()!;

		var documents = await storageProvider.TryGetWellKnownFolderAsync(WellKnownFolder.Documents);
		var file = await storageProvider.SaveFilePickerAsync(new()
		{
			DefaultExtension = ".ifdb",
			FileTypeChoices =
			[
				new FilePickerFileType("InkForge Database File")
				{
					Patterns = [ "*.ifdb" ],
				},
			],
			SuggestedStartLocation = documents,
			Title = "Select InkForge Database Name",
		});

		if (file?.TryGetLocalPath() is not { } filePath)
		{
			return;
		}

		await _workspaceController.OpenWorkspace(filePath, true);
	}

	[RelayCommand]
	private async Task OnOpenNew()
	{
		var storageProvider = this.GetStorageProvider()!;

		var documents = await storageProvider.TryGetWellKnownFolderAsync(WellKnownFolder.Documents);
		var files = await storageProvider.OpenFilePickerAsync(new()
		{
			AllowMultiple = false,
			SuggestedStartLocation = documents,
			FileTypeFilter =
			[
				new FilePickerFileType("InkForge Database File")
				{
					Patterns = [ "*.ifdb" ]
				}
			],
			Title = "Open InkForge Database file"
		});

		if (files.Count != 1)
		{
			return;
		}

		if (files[0].TryGetLocalPath() is not { } filePath)
		{
			return;
		}

		await _workspaceController.OpenWorkspace(filePath, false);
	}
}
