using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AxCopilot.Models;
using AxCopilot.SDK;
using AxCopilot.Services;

namespace AxCopilot.Handlers;

public class FolderAliasHandler : IActionHandler
{
	private readonly SettingsService _settings;

	public string? Prefix => "cd";

	public PluginMetadata Metadata => new PluginMetadata("folder-alias", "폴더 별칭", "1.0", "AX");

	public FolderAliasHandler(SettingsService settings)
	{
		_settings = settings;
	}

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		IEnumerable<LauncherItem> result = from a in _settings.Settings.Aliases
			where a.Type == "folder" && (string.IsNullOrEmpty(query) || a.Key.Contains(query, StringComparison.OrdinalIgnoreCase))
			select new LauncherItem(a.Key, Environment.ExpandEnvironmentVariables(a.Target), null, a, null, "\ue8b7");
		return Task.FromResult(result);
	}

	public Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		if (item.Data is AliasEntry aliasEntry)
		{
			string arguments = Environment.ExpandEnvironmentVariables(aliasEntry.Target);
			Process.Start(new ProcessStartInfo("explorer.exe", arguments)
			{
				UseShellExecute = true
			});
		}
		return Task.CompletedTask;
	}
}
