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 BatchHandler : IActionHandler
{
	private readonly SettingsService _settings;

	public string? Prefix => ">";

	public PluginMetadata Metadata => new PluginMetadata("batch", "명령 실행", "1.0", "AX");

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

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		List<LauncherItem> list = new List<LauncherItem>();
		IEnumerable<LauncherItem> collection = from a in _settings.Settings.Aliases
			where a.Type == "batch" && (string.IsNullOrEmpty(query) || a.Key.Contains(query, StringComparison.OrdinalIgnoreCase))
			select new LauncherItem(a.Key, a.Target, null, a, null, "\ue756");
		list.AddRange(collection);
		if (!string.IsNullOrEmpty(query))
		{
			string text = query.Replace("\"", "\\\"");
			list.Insert(0, new LauncherItem("실행: " + query, "PowerShell에서 직접 실행", null, new AliasEntry
			{
				Type = "batch",
				Target = "powershell -NoProfile -Command \"" + text + "\"",
				ShowWindow = true
			}, null, "\ue756"));
		}
		return Task.FromResult((IEnumerable<LauncherItem>)list);
	}

	public Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		if (item.Data is AliasEntry aliasEntry)
		{
			string text = Environment.ExpandEnvironmentVariables(aliasEntry.Target);
			string[] array = text.Split(' ', 2);
			ProcessStartInfo startInfo = new ProcessStartInfo(array[0])
			{
				Arguments = ((array.Length > 1) ? array[1] : ""),
				UseShellExecute = aliasEntry.ShowWindow,
				CreateNoWindow = !aliasEntry.ShowWindow,
				WindowStyle = ((!aliasEntry.ShowWindow) ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal)
			};
			Process.Start(startInfo);
		}
		return Task.CompletedTask;
	}
}
