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

package keybinding

import (
	"errors"

	backlight "github.com/linuxdeepin/go-dbus-factory/com.deepin.daemon.helper.backlight"
	commonbl "github.com/linuxdeepin/go-lib/backlight/common"
	kbdbl "github.com/linuxdeepin/go-lib/backlight/keyboard"
	. "github.com/linuxdeepin/dde-daemon/keybinding/shortcuts"
)

const backlightTypeKeyboard = 2 // 键盘背光类型标识

// 键盘背光控制器结构体
type KbdLightController struct {
	backlightHelper backlight.Backlight // 背光辅助接口
}

func NewKbdLightController(backlightHelper backlight.Backlight) *KbdLightController {
	return &KbdLightController{
		backlightHelper: backlightHelper,
	}
}

// 获取控制器名称
func (c *KbdLightController) Name() string {
	return "Kbd Light" // 返回控制器名称
}

// 执行键盘背光控制命令
func (c *KbdLightController) ExecCmd(cmd ActionCmd) error {
	switch cmd {
	case KbdLightBrightnessUp: // 增加背光亮度
		return c.changeBrightness(true)
	case KbdLightBrightnessDown: // 降低背光亮度
		return c.changeBrightness(false)
	case KbdLightToggle: // 切换背光开关状态
		return c.toggle()
	default: // 无效命令
		return ErrInvalidActionCmd{cmd}
	}
}

// 获取键盘背光控制器
func getKbdBlController() (*commonbl.Controller, error) {
	controllers, err := kbdbl.List() // 列出所有键盘背光控制器
	if err != nil {
		return nil, err
	}
	if len(controllers) > 0 {
		return controllers[0], nil // 返回第一个控制器
	}
	return nil, errors.New("not found keyboard backlight controller")
}

// 切换键盘背光开关状态（在0和最大值之间切换）
func (c *KbdLightController) toggle() error {
	if c.backlightHelper == nil {
		return ErrIsNil{"KbdLightController.backlightHelper"}
	}

	controller, err := getKbdBlController() // 获取背光控制器
	if err != nil {
		return err
	}
	value, err := controller.GetBrightness() // 获取当前亮度值
	if err != nil {
		return err
	}

	// 在0和最大值之间切换
	if value == 0 {
		value = controller.MaxBrightness // 如果当前是0，则设置为最大值
	} else {
		value = 0 // 否则设置为0
	}
	logger.Debug("[KbdLightController.toggle] will set kbd backlight to:", value)
	// 设置新的亮度值
	return c.backlightHelper.SetBrightness(0, backlightTypeKeyboard, controller.Name, int32(value))
}

var kbdBacklightStep int = 0 // 键盘背光亮度调节步长

// 改变键盘背光亮度
func (c *KbdLightController) changeBrightness(raised bool) error {
	if c.backlightHelper == nil {
		return ErrIsNil{"KbdLightController.backlightHelper"}
	}

	controller, err := getKbdBlController() // 获取背光控制器
	if err != nil {
		return err
	}
	value, err := controller.GetBrightness() // 获取当前亮度值
	if err != nil {
		return err
	}

	maxValue := controller.MaxBrightness // 最大亮度值

	// 计算亮度调节步长（如果尚未计算）
	if kbdBacklightStep == 0 {
		tmp := maxValue / 10 // 计算最大值的10%
		if tmp == 0 {
			tmp = 1 // 确保步长至少为1
		}
		// 四舍五入计算步长
		if float64(maxValue)/10 < float64(tmp)+0.5 {
			kbdBacklightStep = tmp
		} else {
			kbdBacklightStep = tmp + 1
		}
	}
	logger.Debug("[KbdLightController.changeBrightness] kbd backlight info:", value, maxValue, kbdBacklightStep)
	// 根据方向调整亮度值
	if raised {
		value += kbdBacklightStep // 增加亮度
	} else {
		value -= kbdBacklightStep // 降低亮度
	}

	// 确保亮度值在有效范围内
	if value < 0 {
		value = 0
	} else if value > maxValue {
		value = maxValue
	}

	logger.Debug("[KbdLightController.changeBrightness] will set kbd backlight to:", value)
	// 设置新的亮度值
	return c.backlightHelper.SetBrightness(0, backlightTypeKeyboard, controller.Name, int32(value))
}
