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

package keybinding

import (
	"os/exec"
	"sync"

	"github.com/godbus/dbus"
	. "github.com/linuxdeepin/dde-daemon/keybinding/shortcuts"
	display "github.com/linuxdeepin/go-dbus-factory/com.deepin.daemon.display"
	backlight "github.com/linuxdeepin/go-dbus-factory/com.deepin.daemon.helper.backlight"
	"github.com/linuxdeepin/go-gir/gio-2.0"
	"github.com/linuxdeepin/go-lib/strv"
)

const (
	gsKeyOsdAdjustBrightnessState = "osd-adjust-brightness-enabled" // OSD亮度调节状态配置键
)

// OSD亮度调节状态类型
type OsdBrightnessState int32

// Osd亮度调节控制
const (
	BrightnessAdjustEnable OsdBrightnessState = iota
	BrightnessAdjustForbidden
	BrightnessAdjustHidden
)

// 显示控制器结构体
type DisplayController struct {
	display          display.Display        // 显示服务接口
	backlightHelper  backlight.Backlight    // 背光辅助接口
	gsKeyboard       *gio.Settings          // 键盘设置
	brightStatusBusy bool                   // 亮度调节状态繁忙标志
	brightStatusMu   sync.Mutex             // 亮度调节状态互斥锁
	m                *Manager               // 管理器引用
}

func NewDisplayController(backlightHelper backlight.Backlight, sessionConn *dbus.Conn, m *Manager) *DisplayController {
	c := &DisplayController{
		backlightHelper: backlightHelper,
		display:         display.NewDisplay(sessionConn),
		m:               m,
	}
	c.gsKeyboard = gio.NewSettings(gsSchemaKeyboard)
	return c
}

// 获取控制器名称
func (*DisplayController) Name() string {
	return "Display" // 返回控制器名称
}

func (c *DisplayController) ExecCmd(cmd ActionCmd) error {
	c.brightStatusMu.Lock()
	if c.brightStatusBusy {
		c.brightStatusMu.Unlock()
		return nil
	}

	c.brightStatusBusy = true
	c.brightStatusMu.Unlock()

	go func() {
		defer func() {
			c.brightStatusMu.Lock()
			c.brightStatusBusy = false
			c.brightStatusMu.Unlock()
		}()

		var err error
		switch cmd {
		case DisplayModeSwitch:
			// TODO 联想xrandr -q需要修改成X的接口
			if c.m.dmiInfo.ProductName != "" &&
				strv.Strv(c.m.needXrandrQDevice).Contains(c.m.dmiInfo.ProductName) {
				logger.Info("win+p pressed,need run xrandr -q")
				err = exec.Command("xrandr", "-q").Run()
				if err != nil {
					logger.Warning(err)
				}
			}
			var displayList []string
			displayList, err = c.display.ListOutputNames(0)
			if err == nil && len(displayList) > 1 {
				showOSD("SwitchMonitors")
			}
		case MonitorBrightnessUp:
			err = c.changeBrightness(true)
		case MonitorBrightnessDown:
			err = c.changeBrightness(false)
		default:
			err = ErrInvalidActionCmd{cmd}
		}
		if err != nil {
			logger.Warning("Controller exec cmd err:", err)
		}

	}()

	return nil
}

// 环境光调节亮度配置键
const gsKeyAmbientLightAdjustBrightness = "ambient-light-adjust-brightness"

// 改变显示器亮度
func (c *DisplayController) changeBrightness(raised bool) error {
	var osd = "BrightnessUp" // 默认显示亮度增加提示
	if !raised {
		osd = "BrightnessDown" // 亮度降低时显示降低提示
	}
	// 获取OSD亮度调节状态
	var state = OsdBrightnessState(c.gsKeyboard.GetEnum(gsKeyOsdAdjustBrightnessState))

	// 只有当OSD亮度调节状态为启用时，才执行亮度调节操作
	if BrightnessAdjustEnable == state {
		// 获取电源设置
		gs := gio.NewSettings("com.deepin.dde.power")
		// 检查环境光自动调节是否启用
		autoAdjustBrightnessEnabled := gs.GetBoolean(gsKeyAmbientLightAdjustBrightness)
		if autoAdjustBrightnessEnabled {
			// 禁用环境光自动调节
			gs.SetBoolean(gsKeyAmbientLightAdjustBrightness, false)
		}
		gs.Unref() // 释放设置对象

		// 调用显示服务改变亮度
		err := c.display.ChangeBrightness(dbus.FlagNoAutoStart, raised)
		if err != nil {
			return err
		}
	} else if BrightnessAdjustForbidden == state { // 亮度调节被禁止状态
		if raised {
			osd = "BrightnessUpAsh" // 显示灰色亮度增加提示
		} else {
			osd = "BrightnessDownAsh" // 显示灰色亮度降低提示
		}
	} else { // 亮度调节隐藏状态
		return nil
	}

	// 检查是否有支持亮度调节的显示器
	pathList, err := c.display.Monitors().Get(0) // 获取显示器列表
	if err != nil {
		logger.Warning(err)
		return err
	}
	conn, err := dbus.SessionBus() // 获取会话总线
	if err != nil {
		logger.Warning(err)
		return err
	}
	// 遍历所有显示器
	for _, path := range pathList {
		m, err := display.NewMonitor(conn, path) // 创建显示器对象
		if err != nil {
			logger.Warning(err)
			return err
		}
		enable, err := m.Enabled().Get(0) // 检查显示器是否启用
		if err != nil {
			logger.Warning(err)
			return err
		}
		if enable { // 如果显示器已启用
			name, err := m.Name().Get(0) // 获取显示器名称
			if err != nil {
				logger.Warning(err)
				return err
			}
			// 检查显示器是否支持亮度调节
			canSet, err := c.display.CanSetBrightness(0, name)
			if err != nil {
				logger.Warning(err)
				return err
			}
			if canSet { // 如果支持亮度调节
				showOSD(osd) // 显示亮度调节提示
				return nil
			}
		}
	}

	return nil
}
