-- lx-bundle:true

-- This file is part of Lx, created by Liqube <www.liqube.com>
-- Copyright Liqube Audio. All rights reserved.
-- Lx Interim License. See LICENSE for details.

--- Highly experimental WAV preview proof of concept
-- This plugin tests whether Lua work on a real OS thread is useful and practical in Lx
-- Its worker use and structure are temporary experiments, not a stable plugin design
-- @module plugins.wavpreview

local open_handler = require("core.open_handler")
local wav = require("plugins.wavpreview.wav")

--- Accept only WAV encodings that this pure-Lua preview can decode
-- @param request table shared open request
-- @return boolean supported
local function probe_preview(request)
	local doc = request.doc

	if not doc or not doc.filename then
		return false
	end

	local audio = wav.read_file_info(doc.filename)

	if not audio then
		return false
	end

	-- Reuse the compact header metadata when the handler creates its view moments later
	doc.wav_preview_audio = audio

	return true
end

--- Create a WAV preview from the parser result saved by the probe
-- @param request table shared open request
-- @return table view rendered WAV view
local function create_preview(request)
	local WavPreview = require("plugins.wavpreview.view")
	local audio = request.doc.wav_preview_audio
	request.doc.wav_preview_audio = nil

	return WavPreview(request.doc, audio)
end

-- Unsupported WAV codecs continue to the ordinary read-only fallback
open_handler.register({
	name = "wav",
	formats = { "wav" },
	modes = { "preview" },
	probe = probe_preview,
	create_view = create_preview,
})
