--[[

	Snapshot Archive

--]]

Script_Details =
{
	name = "Snapshot Archive",
	author = "Mark Incley",
	version = "2.0.5",
	description = "Randomly selects snapshots from user's archive.",
	webpage = "http://www.inkland.org.uk",
	email = "via form on www.inkland.org.uk",
}

---------------------------------------------------------------------------------------------------
--
---------------------------------------------------------------------------------------------------
function Script_Start()
	local 	err, snap, i, loaded
	local	msg, lastPlayed
	local	lines = {5, 25, 45}
	local	numFailures = 0
	local	numSucceeded = 0;

	-- If there aren't any suitable snapshots in the user's archive folder, run the next script in the playlist.
	if inks.BuildArchiveList() == 0 then
		return
	end

	-- Set the snapshot ball rolling...
	while true do
		-- Make several attempts to load a snapshot. If an error is returned (non zero)
		-- it could be because the snapshot file is damaged, or it's for hardware not
		-- yet supported by InkSpector.
		loaded = false
		for i=1,10 do
			snap, numTimesSelected = inks.SelectFileFromArchive()

			err = inks.LoadSnapshot(snap)
			if err == inks.status.ok then
				loaded = true
				break
			end
		end

		-- Did we load a snapshot?
		if loaded then
			i = string.find(string.reverse(snap), "\\")
			lastPlayed = string.sub(snap, string.len(snap)-i+2)
			NTS = tostring(numTimesSelected)..inks.GetNumberSuffix(numTimesSelected).." time played. "
			creator = inks.GetSnapshotCreator()
			if creator ~= "" then
				NTS = NTS.."Produced by "..creator
			end
			inks.Text(10, lines[2], NTS, 10.0, "green")
			if inks.IsPlayingSnapshot() then
				while inks.IsPlayingSnapshot() do
					-- Showing % progress or filename?
					msg = string.format("%s - %d%%", lastPlayed, inks.GetSnapshotProgress())
					if inks.GetSnapshotPart() > 1 then
						msg = string.format("%s (part %d)", msg, inks.GetSnapshotPart())
					end
					-- Show summary
					msg = string.format("%s (%d good, %d bad)", msg, numSucceeded, numFailures)
					inks.Text(10, lines[1], msg, 0, "cyan")
					inks.Sleep()
				end
				inks.ClearAllText()
				if inks.GetSnapshotCompleted() then
					msg = "playback completed"
					numSucceeded = numSucceeded + 1
				else
					msg = "playback failed"
					numFailures = numFailures + 1
				end
				inks.Text(100, lines[3], lastPlayed.." "..msg , 5.0, "cyan")
			else
				-- Not playing a replay file, so sleep for a few seconds before changing snapshot
				inks.Text(10, lines[1], lastPlayed, 10.0, "cyan")	-- Show the name of the snapshot for a few seconds
				inks.Sleep(10)
				inks.ClearAllText()
			end
		else
			-- Don't rapid-fire attempt to load when there's clearly some issue
			inks.Sleep(1000)
		end
	end
end
