--[[----------------------------------------------------------------------------

ADOBE CONFIDENTIAL
------------------
Copyright 2022 Adobe
All Rights Reserved.

NOTICE: All information contained herein is, and remains
the property of Adobe and its suppliers, if any. The intellectual
and technical concepts contained herein are proprietary to Adobe
and its suppliers and are protected by all applicable intellectual
property laws, including trade secret and copyright laws.
Dissemination of this information or reproduction of this material
is strictly forbidden unless prior written permission is obtained
from Adobe.

----------------------------------------------------------------------------]]--

	-- WF.core
local KSData = require 'KSData'
local KSPathUtils = require 'KSPathUtils'
local WFConfiguration = require 'WFConfiguration'
local WFFileUtils = require 'WFFileUtils'
local WFLogger = require 'WFLogger'

--------------------------------------------------------------------------------

local logger = WFLogger( "WFConfigDotLuaUtils" )

--------------------------------------------------------------------------------

local WFConfigDotLuaUtils = {}

--------------------------------------------------------------------------------

--[[!
	\brief Fetches the contents of the config.lua file.

	\return (string) Returns the contents of the config.lua file as a string.
		If no file exists, returns an empty string.
]]--

function WFConfigDotLuaUtils.getConfigDotLuaContents()

	local parentPath = WFConfiguration.configurationAppDataPath()

	local path = KSPathUtils.child( parentPath, 'config.lua' )

	local contents = ''

	if WFFileUtils.exists( path ) then

		local configData = KSData.memoryMappedContentsOfFile( path )

		contents = tostring( configData )
		
		configData:close()

	end

	return contents

end

--------------------------------------------------------------------------------

--[[!
	\brief Sets the contents of the config.lua file.

	\param contents (string) The new contents of the config.lua file.

	\return boolean - Indicates if the function was successful.
]]--

function WFConfigDotLuaUtils.setConfigDotLuaContents( contents )

	local parentPath = WFConfiguration.configurationAppDataPath()

	local path = KSPathUtils.child( parentPath, 'config.lua' )

	local success = true
	local errorMsg

	if not WFFileUtils.exists( path ) then

		if not WFFileUtils.exists( parentPath ) then
		
			success, errorMsg = pcall( WFFileUtils.mkdir, parentPath )

		end
		
	end

	if success then

		local configData = KSData.make( contents or '' )

		success, errorMsg = pcall( KSData.saveToFile, configData, path )
		
		configData:close()
		
	end
	
	if not success then
	
		logger:warnf( "setConfigDotLuaContents Failed: %s", errorMsg )
	
	end

	return success

end

--------------------------------------------------------------------------------

return WFConfigDotLuaUtils
