using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using AxCopilot.SDK;
using AxCopilot.Services;

namespace AxCopilot.Handlers;

public class MediaHandler : IActionHandler
{
	private record MediaKeyData(byte Vk);

	private const byte VK_MEDIA_PLAY_PAUSE = 179;

	private const byte VK_MEDIA_NEXT_TRACK = 176;

	private const byte VK_MEDIA_PREV_TRACK = 177;

	private const byte VK_VOLUME_UP = 175;

	private const byte VK_VOLUME_DOWN = 174;

	private const byte VK_VOLUME_MUTE = 173;

	private const uint KEYEVENTF_EXTENDEDKEY = 1u;

	private const uint KEYEVENTF_KEYUP = 2u;

	private static readonly List<(string[] Keys, string Title, string Subtitle, byte Vk, string Symbol)> _commands;

	public string? Prefix => "media";

	public PluginMetadata Metadata => new PluginMetadata("MediaControl", "미디어 컨트롤 — media 뒤에 명령어 입력", "1.0", "AX");

	[DllImport("user32.dll")]
	private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, nuint dwExtraInfo);

	public Task<IEnumerable<LauncherItem>> GetItemsAsync(string query, CancellationToken ct)
	{
		string q = query.Trim().ToLowerInvariant();
		IEnumerable<(string[], string, string, byte, string)> source = ((!string.IsNullOrEmpty(q)) ? _commands.Where<(string[], string, string, byte, string)>(((string[] Keys, string Title, string Subtitle, byte Vk, string Symbol) c) => c.Keys.Any((string k) => k.StartsWith(q, StringComparison.OrdinalIgnoreCase)) || c.Title.Contains(q, StringComparison.OrdinalIgnoreCase)) : _commands);
		List<LauncherItem> list = source.Select<(string[], string, string, byte, string), LauncherItem>(((string[] Keys, string Title, string Subtitle, byte Vk, string Symbol) c) => new LauncherItem(c.Title, c.Subtitle, null, new MediaKeyData(c.Vk), null, c.Symbol)).ToList();
		if (list.Count == 0)
		{
			list.Add(new LauncherItem("알 수 없는 명령어", "play · next · prev · vol+ · vol- · mute 중 하나를 입력하세요", null, null, null, "\ue7ba"));
		}
		return Task.FromResult((IEnumerable<LauncherItem>)list);
	}

	public Task ExecuteAsync(LauncherItem item, CancellationToken ct)
	{
		if (!(item.Data is MediaKeyData mediaKeyData))
		{
			return Task.CompletedTask;
		}
		try
		{
			keybd_event(mediaKeyData.Vk, 0, 1u, 0u);
			keybd_event(mediaKeyData.Vk, 0, 3u, 0u);
			LogService.Info($"미디어 키 전송: VK=0x{mediaKeyData.Vk:X2}");
		}
		catch (Exception ex)
		{
			LogService.Warn("미디어 키 전송 실패: " + ex.Message);
		}
		return Task.CompletedTask;
	}

	static MediaHandler()
	{
		int num = 6;
		List<(string[], string, string, byte, string)> list = new List<(string[], string, string, byte, string)>(num);
		CollectionsMarshal.SetCount(list, num);
		Span<(string[], string, string, byte, string)> span = CollectionsMarshal.AsSpan(list);
		span[0] = (new string[3] { "play", "pause", "pp" }, "재생 / 일시정지", "현재 미디어 재생 또는 일시정지", 179, "\ue768");
		span[1] = (new string[2] { "next", ">>" }, "다음 트랙", "다음 곡으로 이동", 176, "\ue893");
		span[2] = (new string[3] { "prev", "previous", "<<" }, "이전 트랙", "이전 곡으로 이동", 177, "\ue892");
		span[3] = (new string[3] { "vol+", "volup", "up" }, "볼륨 올리기", "시스템 볼륨 증가", 175, "\ue995");
		span[4] = (new string[3] { "vol-", "voldown", "down" }, "볼륨 낮추기", "시스템 볼륨 감소", 174, "\ue993");
		span[5] = (new string[2] { "mute", "음소거" }, "음소거 토글", "볼륨 음소거 / 해제", 173, "\ue74f");
		_commands = list;
	}
}
