// SPDX-FileCopyrightText: 2018 - 2022 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

package shortcuts

import (
	"bytes"
	"errors"
	"strconv"
	"strings"

	x "github.com/linuxdeepin/go-x11-client"
	"github.com/linuxdeepin/go-x11-client/util/keysyms"
)

// Keystroke 表示一个按键事件
// 包含修饰键状态、按键字符串、X11键符号和关联的快捷键
// Mods字段忽略mod2(Num_Lock)和lock(Caps_Lock)修饰键
type Keystroke struct {
	Mods     Modifiers  // 修饰键状态（Shift/Ctrl/Alt/Super等）
	Keystr   string     // 按键字符串表示（如"A"、"Enter"）
	Keysym   x.Keysym   // X11键符号
	Shortcut Shortcut   // 关联的快捷键对象

	isKeystrAboveTab bool // 是否为Above_Tab特殊键
}

// DebugString 返回用于调试的字符串表示
func (ks *Keystroke) DebugString() string {
	str := ks.String()
	if ks.Shortcut == nil {
		return "Keystroke{" + str + "}"
	} else {
		return "Keystroke{" + str + " own by " + ks.Shortcut.GetUid() + "}"
	}
}

// Equal 比较两个按键事件是否相等
func (a *Keystroke) Equal(keySymbols *keysyms.KeySymbols, b *Keystroke) bool {
	logger.Debug(a, " equal? ", b)
	if a.Mods != b.Mods {
		logger.Debug("Mods no equal, return false")
		return false
	}
	// ap1.Mods == ap2.Mods
	if a.Keystr == b.Keystr {
		logger.Debug("Key equal, return true")
		return true
	}

	// ap1.Key != ap2.Key
	codes1, err := keySymbols.StringToKeycodes(a.Keystr)
	if err != nil {
		return false
	}
	codes2, err := keySymbols.StringToKeycodes(b.Keystr)
	if err != nil {
		return false
	}

	keycodesEq := isKeycodesEqual(codes1, codes2)
	logger.Debug("keycodesEq:", keycodesEq)
	return keycodesEq
}

// isKeycodesEqual 比较两个键码列表是否相等
func isKeycodesEqual(list1, list2 []x.Keycode) bool {
	logger.Debug("isKeycodesEqual:", list1, list2)
	l1 := len(list1)
	l2 := len(list2)
	if l1 != l2 {
		return false
	}

	for i, v := range list1 {
		if v != list2[i] {
			return false
		}
	}

	return true
}

// MarshalJSON 实现JSON序列化接口
func (ks *Keystroke) MarshalJSON() ([]byte, error) {
	str := ks.String()
	quoted := strconv.Quote(str)
	return []byte(quoted), nil
}

// GetKeyFirstCode 获取按键字符串对应的第一个有效键码
func GetKeyFirstCode(keySymbols *keysyms.KeySymbols, str string) (x.Keycode, error) {
	codes, err := keySymbols.StringToKeycodes(str)
	if err != nil {
		return 0, err
	}
	var code x.Keycode
	for _, kc := range codes {
		if kc != 0 {
			code = kc
			break
		}
	}
	if code == 0 {
		return 0, errors.New("not found keycode")
	}
	//logger.Debugf("GetKeyFirstCode str %q codes: %v code: %d", str, codes, code)
	return code, nil
}

// ToKey 将Keystroke转换为Key结构
func (ks *Keystroke) ToKey(keySymbols *keysyms.KeySymbols) (Key, error) {
	code, err := GetKeyFirstCode(keySymbols, ks.Keystr)
	if err != nil {
		return Key{}, err
	}
	return Key{
		Mods: ks.Mods,
		Code: Keycode(code),
	}, nil
}

// ToKeyList 将Keystroke转换为Key结构列表
func (ks *Keystroke) ToKeyList(keySymbols *keysyms.KeySymbols) ([]Key, error) {
	codes, err := keySymbols.StringToKeycodes(ks.Keystr)
	if err != nil {
		return nil, err
	}
	var keyList []Key
	for _, code := range codes {
		if code == 0 {
			continue
		}
		if strings.HasPrefix(ks.Keystr, "XF86") && keySymbols.GetKeysym(code, 0) != ks.Keysym {
			// XF86 只取基本层级
			continue
		}
		keyList = append(keyList, Key{
			Mods: ks.Mods,
			Code: Keycode(code),
		})
	}
	return keyList, nil
}

// splitKeystroke 分割按键字符串为多个部分
func splitKeystroke(str string) ([]string, error) {
	if str == "" {
		return nil, nil
	}

	var keys []string
	reader := strings.NewReader(str)
	for {
		ch, err := reader.ReadByte()
		if err != nil {
			// eof
			break
		}

		switch ch {
		case '<':
			// 读取修饰键部分
			var key bytes.Buffer
		Loop:
			for {
				ch, err := reader.ReadByte()
				if err != nil {
					// eof
					return nil, errors.New("> not found")
				}
				switch ch {
				case '>':
					break Loop
				case '<':
					return nil, errors.New("unexpect < found")
				default:
					key.WriteByte(ch)
				}
			}
			if key.Len() > 0 {
				keys = append(keys, key.String())
			} else {
				return nil, errors.New("empty modifier found")
			}
		default:
			err := reader.UnreadByte()
			if err != nil {
				logger.Warning("UnreadByte Failed:", err)
			}
			var key bytes.Buffer
			// 读取主键部分
			for {
				ch, err := reader.ReadByte()
				if err != nil {
					break
				}
				switch ch {
				case '<', '>':
					return nil, errors.New("unexpect < or > found")
				default:
					key.WriteByte(ch)
				}
			}
			keys = append(keys, key.String())
		}
	}
	return keys, nil
}

// ParseKeystroke 解析按键字符串为Keystroke结构
// 示例：
//   <Super>L -> mods (mod4) key L
//   <Super>% -> mods (mod4, shift) key %
//   <Control><Alt>T -> mods (control,mod1) key T
//   <Control><shift>T -> mods(control,shift) key T
//   <Control>> -> mods(control) key >
func ParseKeystroke(keystroke string) (*Keystroke, error) {
	parts, err := splitKeystroke(keystroke)
	if err != nil {
		return nil, err
	}
	if len(parts) == 0 {
		return nil, errors.New("keystroke is empty")
	}

	str := parts[len(parts)-1]
	if str == "Space" {
		str = "space"
	}
	// 检查按键有效性
	var sym x.Keysym
	var isKeystrAboveTab bool
	if str == "Above_Tab" {
		isKeystrAboveTab = true
	} else {
		var ok bool
		sym, ok = keysyms.StringToKeysym(str)
		if !ok {
			return nil, errors.New("bad key " + str)
		}
	}

	var mods Modifiers
	for _, part := range parts[:len(parts)-1] {
		switch strings.ToLower(part) {
		case "shift":
			mods |= keysyms.ModMaskShift
		case "control":
			mods |= keysyms.ModMaskControl
		case "alt":
			mods |= keysyms.ModMaskAlt
		case "super":
			mods |= keysyms.ModMaskSuper
		default:
			return nil, errors.New("unknown mod " + part)
		}
	}

	return &Keystroke{
		Mods:             mods,
		Keystr:           str,
		Keysym:           sym,
		isKeystrAboveTab: isKeystrAboveTab,
	}, nil
}

// ParseKeystrokes 批量解析按键字符串为Keystroke列表
func ParseKeystrokes(keystrokes []string) []*Keystroke {
	result := make([]*Keystroke, 0, len(keystrokes))
	for _, keystroke := range keystrokes {
		parsed, err := ParseKeystroke(keystroke)
		if err == nil {
			result = append(result, parsed)
		}
		// TODO else warning
	}
	return result
}

// String 返回按键的标准字符串表示
func (ks *Keystroke) String() string {
	var keys []string
	mods := ks.Mods
	if mods&keysyms.ModMaskShift > 0 {
		keys = append(keys, "<Shift>")
	}
	if mods&keysyms.ModMaskControl > 0 {
		keys = append(keys, "<Control>")
	}
	if mods&keysyms.ModMaskAlt > 0 {
		keys = append(keys, "<Alt>")
	}
	if mods&keysyms.ModMaskSuper > 0 {
		keys = append(keys, "<Super>")
	}

	keys = append(keys, ks.Keystr)
	return strings.Join(keys, "")
}

// searchString 返回用于搜索的字符串表示
func (ks *Keystroke) searchString() string {
	var strs []string
	mods := ks.Mods
	if mods&keysyms.ModMaskShift > 0 {
		strs = append(strs, "shift")
	}
	if mods&keysyms.ModMaskControl > 0 {
		strs = append(strs, "ctrl")
	}
	if mods&keysyms.ModMaskAlt > 0 {
		strs = append(strs, "alt")
	}
	if mods&keysyms.ModMaskSuper > 0 {
		strs = append(strs, "super")
	}

	visibleChar, ok := keysyms.KeysymVisibleCharMap[ks.Keysym]
	if ok {
		if visibleChar == keysyms.XK_space {
			strs = append(strs, "space")
		} else {
			strs = append(strs, strings.ToLower(string(visibleChar)))
		}
	} else {
		keyStr := fixSpecialKeyStr(ks.Keystr)
		strs = append(strs, strings.ToLower(keyStr))
	}

	return strings.Join(strs, "")
}

// fixSpecialKeyStr 处理特殊键值字符串
func fixSpecialKeyStr(keyStr string) string {
	// 处理特殊键值，搜索时，去除按键值的前后缀，例如Super_L,搜索super即可
	res := strings.TrimSuffix(keyStr, "_L")
	res = strings.TrimSuffix(res, "_R")
	res = strings.TrimPrefix(res, "KP_")
	return res
}

// isGoodNoMods 检查无修饰键的按键是否有效
func isGoodNoMods(str string, sym x.Keysym) bool {
	// 功能键或特殊功能键
	if keysyms.IsFunctionKey(sym) || keysyms.IsMiscFunctionKey(sym) {
		return true
	}

	switch sym {
	case keysyms.XK_BackSpace,
		keysyms.XK_Delete,
		keysyms.XK_Super_L,
		keysyms.XK_Super_R,
		keysyms.XK_Pause:
		return true
	}

	return strings.HasPrefix(str, "XF86")
}

// isGoodModShift 检查带Shift修饰键的按键是否有效
func isGoodModShift(str string, sym x.Keysym) bool {
	// 功能键、特殊功能键或光标键
	if keysyms.IsFunctionKey(sym) || keysyms.IsMiscFunctionKey(sym) || keysyms.IsCursorKey(sym) {
		return true
	}

	switch sym {
	case keysyms.XK_BackSpace,
		keysyms.XK_space,
		keysyms.XK_Delete,
		keysyms.XK_Sys_Req,
		keysyms.XK_Escape,
		keysyms.XK_Tab:
		return true
	}

	return strings.HasPrefix(str, "XF86")
}

// IsGood 检查按键组合是否有效
func (ks *Keystroke) IsGood() bool {
	if ks.Mods == 0 {
		return isGoodNoMods(ks.Keystr, ks.Keysym)
	}
	// else ks.Mod > 0
	if keysyms.IsModifierKey(ks.Keysym) {
		return false
	}
	if ks.Mods == keysyms.ModMaskShift {
		return isGoodModShift(ks.Keystr, ks.Keysym)
	}

	return true
}

// fix 修正按键表示
func (ks *Keystroke) fix() *Keystroke {
	logger.Debug("before fix", ks)
	var key string
	switch ks.Keystr {
	case "KP_Prior":
		key = "KP_Page_Up"
	case "KP_Next":
		key = "KP_Page_Down"
	case "Prior":
		key = "Page_Up"
	case "Next":
		key = "Page_Down"
	case "ISO_Left_Tab":
		key = "Tab"
	default:
		key = ks.Keystr
	}

	sym, _ := keysyms.StringToKeysym(key)
	_, upperSym := keysyms.ConvertCase(sym)
	if sym != upperSym {
		key, _ = keysyms.KeysymToString(upperSym)
	}

	if ks.Mods > 0 && ks.Mods&^keysyms.ModMaskSuper == 0 {
		// ks is <Super>Super_L or <Super>Super_R
		if ks.Keysym == keysyms.XK_Super_L || ks.Keysym == keysyms.XK_Super_R {
			// 清除修饰键
			ks.Mods = 0
		}
	}
	ks.Keystr = key
	ks.Keysym = upperSym
	logger.Debug("after fix", ks)
	return ks
}
