using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using AxCopilot.SDK;
using AxCopilot.Views;

namespace AxCopilot.Handlers;

public class RunHandler : IActionHandler
{
	public string? Prefix => "^";

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

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		string text = query.Trim();
		if (string.IsNullOrEmpty(text))
		{
			return Task.FromResult((IEnumerable<LauncherItem>)new _003C_003Ez__ReadOnlyArray<LauncherItem>(new LauncherItem[5]
			{
				new LauncherItem("Windows 실행 명령", "Win+R 실행 창과 동일 · 명령어 입력 후 Enter", null, null, null, "\ue7c4"),
				new LauncherItem("^ notepad", "메모장 실행", null, null, null, "\ue946"),
				new LauncherItem("^ cmd", "명령 프롬프트", null, null, null, "\ue946"),
				new LauncherItem("^ control", "제어판", null, null, null, "\ue946"),
				new LauncherItem("^ calc", "계산기", null, null, null, "\ue946")
			}));
		}
		return Task.FromResult((IEnumerable<LauncherItem>)new _003C_003Ez__ReadOnlySingleElementList<LauncherItem>(new LauncherItem("실행: " + text, "Enter → Windows 실행 명령으로 실행", null, "__RUN__" + text, null, "\ue7c4")));
	}

	public Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		if (!(item.Data is string text) || !text.StartsWith("__RUN__"))
		{
			return Task.CompletedTask;
		}
		string text2 = text;
		int length = "__RUN__".Length;
		string text3 = text2.Substring(length, text2.Length - length).Trim();
		if (string.IsNullOrEmpty(text3))
		{
			return Task.CompletedTask;
		}
		try
		{
			Process.Start(new ProcessStartInfo(text3)
			{
				UseShellExecute = true
			})?.Dispose();
		}
		catch (Exception ex)
		{
			CustomMessageBox.Show("실행 실패: " + ex.Message, "AX Copilot", MessageBoxButton.OK, MessageBoxImage.Hand);
		}
		return Task.CompletedTask;
	}
}
