package model

import "sync"

// Experiments are optional functionality that can be enabled/disabled by an application either completely or individually.
// examples of experiments include File Sharing, Profile Images and Groups.
type Experiments struct {
	enabled     bool
	experiments *sync.Map
}

// InitExperiments encapsulates a set of experiments separate from their storage in GlobalSettings.
func InitExperiments(enabled bool, experiments map[string]bool) Experiments {

	syncExperiments := new(sync.Map)
	for experiment, set := range experiments {
		syncExperiments.Store(experiment, set)
	}

	return Experiments{
		enabled:     enabled,
		experiments: syncExperiments,
	}
}

// IsEnabled is a convenience function that takes in an experiment and returns true if it is enabled. Experiments
// are only enabled if both global experiments are turned on and if the specific experiment is also turned on.
// The one exception to this is experiments that have been promoted to default functionality which may be turned on
// even if experiments turned off globally. These experiments are defined by DefaultEnabledFunctionality.
func (e *Experiments) IsEnabled(experiment string) bool {
	if !e.enabled {
		// todo handle default-enabled functionality
		return false
	}

	enabled, exists := e.experiments.Load(experiment)
	if !exists {
		return false
	}
	return enabled.(bool)
}
