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

package shortcuts

import (
	"errors"
	"os"
	"strings"

	wm "github.com/linuxdeepin/go-dbus-factory/com.deepin.wm"
	"github.com/linuxdeepin/dde-daemon/keybinding/util"
)

// kWinShortcut 表示KWin窗口管理器的快捷键
type kWinShortcut struct {
	BaseShortcut
	wm wm.Wm // 窗口管理器接口
}

// newKWinShortcut 创建新的KWin快捷键对象
func newKWinShortcut(id, name string, keystrokes []string, wm wm.Wm) *kWinShortcut {
	return &kWinShortcut{
		BaseShortcut: BaseShortcut{
			Id:         id,
			Type:       ShortcutTypeWM,
			Name:       name,
			Keystrokes: ParseKeystrokes(keystrokes),
		},
		wm: wm,
	}
}

// ReloadKeystrokes 重新加载KWin快捷键的按键设置
func (ks *kWinShortcut) ReloadKeystrokes() bool {
	oldVal := ks.GetKeystrokes()
	keystrokes, err := ks.wm.GetAccel(0, ks.Id)
	if err != nil {
		logger.Warningf("failed to get accel for %s: %v", ks.Id, err)
		return false
	}
	// Wayland环境特殊处理
	sessionType := os.Getenv("XDG_SESSION_TYPE")
	if strings.Contains(sessionType, "wayland") {
		if len(keystrokes) != 0 && strings.Contains(keystrokes[0], "SysReq") {
			keystrokes[0] = strings.Replace(keystrokes[0], "SysReq", "<Alt>Print", 1)
		}
		// 启动器特殊处理
		if ks.Id == "launcher" {
			keystrokes[0] = "<Super_L>"
		}
		// 系统监视器特殊处理
		if ks.Id == "system-monitor" {
			for i := 0; i < len(keystrokes); i++ {
				keystrokes[i] = strings.Replace(keystrokes[i], "Esc", "Escape", 1)
			}
		}
	}
	newVal := ParseKeystrokes(keystrokes)
	ks.setKeystrokes(newVal)
	return !keystrokesEqual(oldVal, newVal)
}

// SaveKeystrokes 保存KWin快捷键的按键设置
func (ks *kWinShortcut) SaveKeystrokes() error {
	accelJson, err := util.MarshalJSON(util.KWinAccel{
		Id:         ks.Id,
		Keystrokes: ks.getKeystrokesStrv(),
	})
	if err != nil {
		return err
	}

	ok, err := ks.wm.SetAccel(0, accelJson)
	if !ok {
		return errors.New("wm.SetAccel failed, id: " + ks.Id)
	}
	return err
}

// ShouldEmitSignalChanged 是否触发改变信号
func (ks *kWinShortcut) ShouldEmitSignalChanged() bool {
	return true
}
