package config

import (
	"sync"
	"testing"
	"time"
)

// should be run with -race
func TestConcurrentConfigAccess(t *testing.T) {
	i := InitializeEmpty()

	const workers = 8
	const loops = 200
	var wg sync.WaitGroup
	for k := 0; k < workers; k++ {
		wg.Add(1)
		go func(wk int) {
			for l := 0; l < loops; l++ {
				start := time.Now()
				if err := i.SetInitialConfig(); err != nil {
					t.Errorf("Failure setting initial configuration in worker %v iteration %v: %v", wk, l, err)
				}

				i.HasCredentials()
				i.ValidateCredentials("", "")
				i.GetConfigFile()
				i.GetConfigPath()
				i.GetDefaultDatabaseFilePath()
				i.Set(BackupDirectoryPath, i.GetBackupDirectoryPath())
				i.GetStashPaths()
				_ = i.ValidateStashBoxes(nil)
				_ = i.Validate()
				_ = i.ActivatePublicAccessTripwire("")
				i.Set(Cache, i.GetCachePath())
				i.Set(Generated, i.GetGeneratedPath())
				i.Set(Metadata, i.GetMetadataPath())
				i.Set(Database, i.GetDatabasePath())

				// these must be set as strings since the original values are also strings
				// setting them as []byte will cause the returned string to be corrupted
				i.Set(JWTSignKey, string(i.GetJWTSignKey()))
				i.Set(SessionStoreKey, string(i.GetSessionStoreKey()))

				i.GetDefaultScrapersPath()
				i.Set(Exclude, i.GetExcludes())
				i.Set(ImageExclude, i.GetImageExcludes())
				i.Set(VideoExtensions, i.GetVideoExtensions())
				i.Set(ImageExtensions, i.GetImageExtensions())
				i.Set(GalleryExtensions, i.GetGalleryExtensions())
				i.Set(CreateGalleriesFromFolders, i.GetCreateGalleriesFromFolders())
				i.Set(Language, i.GetLanguage())
				i.Set(VideoFileNamingAlgorithm, i.GetVideoFileNamingAlgorithm())
				i.Set(ScrapersPath, i.GetScrapersPath())
				i.Set(ScraperUserAgent, i.GetScraperUserAgent())
				i.Set(ScraperCDPPath, i.GetScraperCDPPath())
				i.Set(ScraperCertCheck, i.GetScraperCertCheck())
				i.Set(ScraperExcludeTagPatterns, i.GetScraperExcludeTagPatterns())
				i.Set(StashBoxes, i.GetStashBoxes())
				i.GetDefaultPluginsPath()
				i.Set(PluginsPath, i.GetPluginsPath())
				i.Set(Host, i.GetHost())
				i.Set(Port, i.GetPort())
				i.Set(ExternalHost, i.GetExternalHost())
				i.Set(PreviewSegmentDuration, i.GetPreviewSegmentDuration())
				i.Set(ParallelTasks, i.GetParallelTasks())
				i.Set(ParallelTasks, i.GetParallelTasksWithAutoDetection())
				i.Set(PreviewAudio, i.GetPreviewAudio())
				i.Set(PreviewSegments, i.GetPreviewSegments())
				i.Set(PreviewExcludeStart, i.GetPreviewExcludeStart())
				i.Set(PreviewExcludeEnd, i.GetPreviewExcludeEnd())
				i.Set(PreviewPreset, i.GetPreviewPreset())
				i.Set(MaxTranscodeSize, i.GetMaxTranscodeSize())
				i.Set(MaxStreamingTranscodeSize, i.GetMaxStreamingTranscodeSize())
				i.Set(ApiKey, i.GetAPIKey())
				i.Set(Username, i.GetUsername())
				i.Set(Password, i.GetPasswordHash())
				i.GetCredentials()
				i.Set(MaxSessionAge, i.GetMaxSessionAge())
				i.Set(CustomServedFolders, i.GetCustomServedFolders())
				i.Set(LegacyCustomUILocation, i.GetUILocation())
				i.Set(MenuItems, i.GetMenuItems())
				i.Set(SoundOnPreview, i.GetSoundOnPreview())
				i.Set(WallShowTitle, i.GetWallShowTitle())
				i.Set(CustomPerformerImageLocation, i.GetCustomPerformerImageLocation())
				i.Set(WallPlayback, i.GetWallPlayback())
				i.Set(MaximumLoopDuration, i.GetMaximumLoopDuration())
				i.Set(AutostartVideo, i.GetAutostartVideo())
				i.Set(ShowStudioAsText, i.GetShowStudioAsText())
				i.Set(legacyImageLightboxSlideshowDelay, *i.GetImageLightboxOptions().SlideshowDelay)
				i.Set(ImageLightboxSlideshowDelay, *i.GetImageLightboxOptions().SlideshowDelay)
				i.GetCSSPath()
				i.GetCSS()
				i.GetJavascriptPath()
				i.GetJavascript()
				i.GetCustomLocalesPath()
				i.GetCustomLocales()
				i.Set(CSSEnabled, i.GetCSSEnabled())
				i.Set(CSSEnabled, i.GetCustomLocalesEnabled())
				i.Set(HandyKey, i.GetHandyKey())
				i.Set(UseStashHostedFunscript, i.GetUseStashHostedFunscript())
				i.Set(DLNAServerName, i.GetDLNAServerName())
				i.Set(DLNADefaultEnabled, i.GetDLNADefaultEnabled())
				i.Set(DLNADefaultIPWhitelist, i.GetDLNADefaultIPWhitelist())
				i.Set(DLNAInterfaces, i.GetDLNAInterfaces())
				i.Set(DLNAPort, i.GetDLNAPort())
				i.Set(LogFile, i.GetLogFile())
				i.Set(LogOut, i.GetLogOut())
				i.Set(LogLevel, i.GetLogLevel())
				i.Set(LogAccess, i.GetLogAccess())
				i.Set(MaxUploadSize, i.GetMaxUploadSize())
				i.Set(FunscriptOffset, i.GetFunscriptOffset())
				i.Set(DefaultIdentifySettings, i.GetDefaultIdentifySettings())
				i.Set(DeleteGeneratedDefault, i.GetDeleteGeneratedDefault())
				i.Set(DeleteFileDefault, i.GetDeleteFileDefault())
				i.Set(dangerousAllowPublicWithoutAuth, i.GetDangerousAllowPublicWithoutAuth())
				i.Set(SecurityTripwireAccessedFromPublicInternet, i.GetSecurityTripwireAccessedFromPublicInternet())
				i.Set(DisableDropdownCreatePerformer, i.GetDisableDropdownCreate().Performer)
				i.Set(DisableDropdownCreateStudio, i.GetDisableDropdownCreate().Studio)
				i.Set(DisableDropdownCreateTag, i.GetDisableDropdownCreate().Tag)
				i.Set(DisableDropdownCreateMovie, i.GetDisableDropdownCreate().Movie)
				i.Set(AutostartVideoOnPlaySelected, i.GetAutostartVideoOnPlaySelected())
				i.Set(ContinuePlaylistDefault, i.GetContinuePlaylistDefault())
				i.Set(PythonPath, i.GetPythonPath())
				t.Logf("Worker %v iteration %v took %v", wk, l, time.Since(start))
			}
			wg.Done()
		}(k)
	}

	wg.Wait()
}
