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

namespace AxCopilot.Handlers;

public class WorkspaceHandler : IActionHandler
{
	private readonly ContextManager _context;

	private readonly SettingsService _settings;

	public string? Prefix => "~";

	public PluginMetadata Metadata => new PluginMetadata("workspace", "워크스페이스", "1.0", "AX");

	public WorkspaceHandler(ContextManager context, SettingsService settings)
	{
		_context = context;
		_settings = settings;
	}

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		string[] array = query.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
		if (array.Length == 0 || string.IsNullOrEmpty(query))
		{
			List<LauncherItem> list = _settings.Settings.Profiles.Select((WorkspaceProfile p) => new LauncherItem("~" + p.Name, $"{p.Windows.Count}개 창  |  {p.CreatedAt:MM/dd HH:mm}", null, p, null, "\ue8a1")).ToList();
			if (list.Count == 0)
			{
				list.Add(new LauncherItem("저장된 프로필 없음", "~save <이름> 으로 현재 배치를 저장하세요", null, null, null, "\ue946"));
			}
			return Task.FromResult((IEnumerable<LauncherItem>)list);
		}
		string text = array[0].ToLowerInvariant();
		if (text == "save")
		{
			string text2 = ((array.Length > 1) ? array[1] : "default");
			return Task.FromResult((IEnumerable<LauncherItem>)new LauncherItem[1]
			{
				new LauncherItem("현재 창 배치를 '" + text2 + "'으로 저장", "Enter로 확인", null, new WorkspaceAction(WorkspaceActionType.Save, text2), null, "\ue74e")
			});
		}
		if (text == "delete" && array.Length > 1)
		{
			return Task.FromResult((IEnumerable<LauncherItem>)new LauncherItem[1]
			{
				new LauncherItem("프로필 '" + array[1] + "' 삭제", "Enter로 확인 (되돌릴 수 없습니다)", null, new WorkspaceAction(WorkspaceActionType.Delete, array[1]), null, "\ue74d")
			});
		}
		if (text == "rename" && array.Length > 2)
		{
			return Task.FromResult((IEnumerable<LauncherItem>)new LauncherItem[1]
			{
				new LauncherItem($"프로필 '{array[1]}' → '{array[2]}'로 이름 변경", "Enter로 확인", null, new WorkspaceAction(WorkspaceActionType.Rename, array[1], array[2]), null, "\ue8ac")
			});
		}
		IEnumerable<LauncherItem> result = from p in _settings.Settings.Profiles
			where p.Name.Contains(query, StringComparison.OrdinalIgnoreCase)
			select new LauncherItem("~" + p.Name + " 복원", $"{p.Windows.Count}개 창  |  {p.CreatedAt:MM/dd HH:mm}", null, new WorkspaceAction(WorkspaceActionType.Restore, p.Name), null, "\ue72c");
		return Task.FromResult(result);
	}

	public async Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		object data = item.Data;
		if (!(data is WorkspaceAction action))
		{
			return;
		}
		switch (action.Type)
		{
		case WorkspaceActionType.Restore:
			LogService.Info("복원 결과: " + (await _context.RestoreProfileAsync(action.Name, ct)).Message);
			break;
		case WorkspaceActionType.Save:
			_context.CaptureProfile(action.Name);
			break;
		case WorkspaceActionType.Delete:
			_context.DeleteProfile(action.Name);
			break;
		case WorkspaceActionType.Rename:
			if (action.NewName != null)
			{
				_context.RenameProfile(action.Name, action.NewName);
			}
			break;
		}
	}
}
