# signature { license=0, seed=277031123, key="6e77be5dbbe5a56b7ede3e5c79aca552" }
-- ----------------------------------------------------------------------------



local api = import( 'api' )



api.token = nil

log( i18n("Contacting LMS for new licenses") )



local function setEmail( result )
	_G.Email = result
	local f = io.open( 'email' )
	if f then
		f:write( result )
		f:close()
	end
end




local result
local response = api.decode( api.get( '/api/v1/Devices/'..cfg.DeviceId..'/Licenses' ) )
local data = response.data
if data and response.success then
	if _G.immediate
	or data.updateKey and data.updateKey ~= cfg.updateKey then
		log( i18n("LMS provided new licenses") )
		local lic = data.license and data.license.data
		if lic then
			local webpro = import( 'webpro' )


			lic = import( 'mime' ).unb64( lic )



			local SessionId = webpro.login( cfg.XmlProUserID, cfg:password( 'XmlPro' ) )
			if not SessionId then
				result = i18n("Could not log on to WebPRO")
				log ( result )

				setEmail( result )
			else
				result = webpro.uploadLIC( lic )
				log ( i18n("License file uploaded, WebPRO result:"), result )

				setEmail( result )
				webpro.logout()

				if result == 'License registered successfully.' then
					cfg.updateKey = data.updateKey
				end
			end


			_G.Email = result
		end
	else
		log( i18n("LMS has no new licenses provided") )
	end



	local contact = data.dealer
	if contact then
		if contact.name then cfg.DealerName = contact.name end
		if contact.contactEmail then cfg.DealerEmail = contact.contactEmail end
	end

	contact = data.customer
	if contact then
		if contact.name then cfg.CustomerName = contact.name end
		if contact.contactEmail then cfg.CustomerEmail = contact.contactEmail end
	end


	local requestInterval = data.suggestedRequestInterval
	if requestInterval then
		cfg.requestInterval = 3600 * requestInterval
	end
else
	_G.Email = i18n("Could not retrieve license file: ") .. ( response.message or i18n("no connection") )
	log( _G.Email )
end


if (cfg.requestTimeRange or -1) >= 0 then

	local nextTime = os.date( '*t' )
	nextTime.day  = nextTime.day + 1
	nextTime.hour = cfg.requestTimeRange
	nextTime.min  = math.random( 0, 59 )
	nextTime.sec  = math.random( 0, 59 )
	cfg.nextRequestTime = os.time( nextTime )
else

	cfg.nextRequestTime = cfg.nextRequestTime + cfg.requestInterval


	if data and data.serverTime and data.suggestedTimeSlot then

		local h, m, s = data.serverTime:match( '(%d%d):(%d%d):(%d%d)' )
		local serverTime = ( 60 * h + m ) * 60 + s

		h, m = data.suggestedTimeSlot:match( '(%d%d):(%d%d)' )
		local nextSlot = ( 60 * h + m ) * 60


		local nextTime = serverTime + 3600 * data.suggestedRequestInterval


		nextTime = nextTime - nextTime % 86400 + nextSlot


		cfg.nextRequestTime = os.time() + ( nextTime - serverTime )
	end
end

cfg:write()

log( os.date( i18n("Next LMS access will be at %Y-%m-%d %H:%M:%S"), cfg.nextRequestTime ) )
