// Copyright 2022 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0

package configuration

import (
	"github.com/imdario/mergo"
)

// New NewSetting creates a new configuration setting
// with the given defaults.
func New[C any](defaults C) *Settings[C] {

	s := &Settings[C]{}

	defer func() {
		s.notifyErrorHooks()
	}()

	s.initDefaults()

	if err := mergo.Merge(&defaults, s.config); err != nil {
		s.errors = append(s.errors, err)
	}

	s.config = defaults

	err := validateConfig[C](defaults)
	if err != nil {
		s.errors = append(s.errors, err)
		var r C
		s.config = r
	}

	initFileBackend(&s.files)
	return s
}

// SetMnemonic Set the mnemonic
// The mnemonic is used to identify the configuration in the configuration file
func (s *Settings[C]) SetMnemonic(mnemonic string) *Settings[C] {

	defer func() {
		s.notifyErrorHooks()
	}()

	if mnemonic == "" {
		s.errors = append(s.errors, MnemonicEmptyError)
	} else {
		s.mnemonic = mnemonic
	}
	return s
}

// Config returns the configuration
// Remember that the configuration is a copy of the original configuration.
// Changes to the configuration will not be reflected in the original configuration.
func (s *Settings[C]) Config() C {

	s.Lock()
	defer s.Unlock()

	return s.config
}