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

package audio

import (
	"time"

	"github.com/linuxdeepin/dde-daemon/loader"
	"github.com/linuxdeepin/go-lib/dbusutil"
	"github.com/linuxdeepin/go-lib/log"
	"github.com/linuxdeepin/go-lib/utils"
	"golang.org/x/xerrors"
)

var (
	logger       = log.NewLogger("daemon/audio") // 音频模块日志记录器
	nodeF1KeyLED = "/proc/uos/F1_KEY_LED"        // F1键LED节点路径
	nodeF4KeyLED = "/proc/uos/F4_KEY_LED"        // F4键LED节点路径
	nodeF7KeyLED = "/sys/devices/platform/smartcc/leds/platform::micmute/brightness" // F7键LED节点路径 麦克风
	nodeF8KeyLED = "/sys/devices/platform/smartcc/leds/platform::mute/brightness"    // F8键LED节点路径 扬声器
)

// init 模块初始化函数
// 注册音频模块并检查LED节点文件是否存在
func init() {
	loader.Register(NewModule(logger))
	if !utils.IsFileExist(nodeF1KeyLED) {
		logger.Infof("%s is not exist", nodeF1KeyLED)
	}
	if !utils.IsFileExist(nodeF4KeyLED) {
		logger.Infof("%s is not exist", nodeF4KeyLED)
	}
	if !utils.IsFileExist(nodeF7KeyLED) {
		logger.Infof("%s is not exist", nodeF7KeyLED)
	}
	if !utils.IsFileExist(nodeF8KeyLED) {
		logger.Infof("%s is not exist", nodeF8KeyLED)
	}
}

// Module 音频模块结构体
type Module struct {
	*loader.ModuleBase
	audio *Audio // 音频管理实例
}

// NewModule 创建新的音频模块实例
// logger: 日志记录器
func NewModule(logger *log.Logger) *Module {
	var d = new(Module)
	d.ModuleBase = loader.NewModuleBase("audio", d, logger)
	return d
}

// GetDependencies 获取模块依赖列表
// 音频模块没有依赖其他模块
func (*Module) GetDependencies() []string {
	return []string{}
}

// start 启动音频模块
// 包括启动脉冲音频服务、初始化音频管理、导出DBus接口等
func (m *Module) start() error {
	err := startPulseaudio(5) // 为了保证蓝牙模块依赖audio模块,并且audio模块启动pulseaudio完成.
	if err != nil {
		err = xerrors.Errorf("failed to start pulseaudio: %w", err)
		return err
	}

	service := loader.GetService()
	m.audio = newAudio(service)
	err = m.audio.init()
	if err != nil {
		logger.Warning("failed to init audio module:", err)
		return nil
	}

	err = service.Export(dbusPath, m.audio, m.audio.syncConfig)
	if err != nil {
		return err
	}
	err = service.RequestName(dbusServiceName)
	if err != nil {
		return err
	}

	so := service.GetServerObject(m.audio)
	err = so.SetWriteCallback(m.audio, "ReduceNoise", m.audio.writeReduceNoise)
	err = so.SetWriteCallback(m.audio, "MuteInputWhenLidClose", m.audio.writeMuteWhenLidClose)

	err = m.audio.syncConfig.Register()
	if err != nil {
		logger.Warning("failed to register for deepin sync:", err)
	}
	return nil
}

// Start 启动模块的公共接口
// 如果音频实例已存在则直接返回，否则等待音效播放器退出后启动
func (m *Module) Start() error {
	if m.audio != nil {
		return nil
	}
	waitSoundThemePlayerExit()
	err := m.start()
	if err != nil {
		logger.Warning(err)
	}
	return nil
}

// Stop 停止模块
// 销毁音频实例并释放相关资源
func (m *Module) Stop() error {
	if m.audio == nil {
		return nil
	}

	m.audio.destroy()

	service := loader.GetService()
	err := service.StopExport(m.audio)
	if err != nil {
		logger.Warning(err)
	}

	err = service.ReleaseName(dbusServiceName)
	if err != nil {
		logger.Warning(err)
	}

	m.audio = nil
	return nil
}

// waitSoundThemePlayerExit 等待音效主题播放器退出
// 确保音频模块启动前没有其他音频服务占用资源
func waitSoundThemePlayerExit() {
	srv, err := dbusutil.NewSystemService()
	if err != nil {
		logger.Warning("Failed to connect system bus:", err)
		return
	}

	for {
		var owner string
		owner, err = srv.GetNameOwner("com.deepin.api.SoundThemePlayer")
		if err != nil {
			return
		}
		logger.Info("Owner:", owner)
		time.Sleep(time.Millisecond * 800)
	}
}
