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

package grub2

import (
	"sync"

	"github.com/linuxdeepin/go-lib/dbusutil"
)

// Theme is a dbus object which provide properties and methods to
// setup deepin grub2 theme.
type Fstart struct {
	g       *Grub2
	service *dbusutil.Service

	PropsMu sync.RWMutex
	// props:
	IsSkipGrub   bool
}

// NewTheme create Theme object.
func NewFstart(g *Grub2) *Fstart {
	fstart := &Fstart{}
	fstart.g = g
	fstart.service = g.service

	isSkipGrub, lineNum := getFstartState()
	if lineNum == -1 {
		logger.Warning(deepinFstartFile + "is illegal!")
	}
	logger.Infof("/etc/default/grub.d/15_deepin_fstart.cfg isSkipGrub : %v, dconfig of org.deepin.dde.daemon.grub2 fstartSkipGrub : %v.", isSkipGrub, g.fstartSkipGrub)
	if g.firstUsed {
		fstart.IsSkipGrub = isSkipGrub

		// 将/etc/default/grub.d/15_deepin_fstart.cfg获取的值，设置到dsg
		if isSkipGrub != g.fstartSkipGrub {
			logger.Warning("Need use 15_deepin_fstart.cfg set to dconfig")
			err := g.setDsgValue(dsgFstartSkipGrub, isSkipGrub)
			if err != nil {
				logger.Warning(err)
			}
		}

		// 只使用一次，用于初次使用同步配置数据
		err := g.setDsgValue(dsgFirstUsed, false)
		if err != nil {
			logger.Warning(err)
		}
	} else {
		fstart.IsSkipGrub = g.fstartSkipGrub

		// 将dsg配置的值，设置到/etc/default/grub.d/15_deepin_fstart.cfg
		if isSkipGrub != g.fstartSkipGrub {
			logger.Warning("Need use dconfig set to 15_deepin_fstart.cfg")
			err := setFstartState(fstart.IsSkipGrub)
			if err != nil {
				logger.Warning(err)
			}
			// 触发update-grub
			g.addModifyTask(modifyTask{})
		}
	}

	return fstart
}
