-- lx-bundle:true

--- XLSX extraction commands for binary-viewer documents.
-- @module plugins.xlsxutils

local core = require("core")
local command = require("core.command")
local Doc = require("core.doc")
local reader = require("plugins.xlsxutils.reader")

local function active_xlsx_doc()
	local view = core.active_view
	local doc = view and view.doc
	local filename = doc and doc.filename

	if type(filename) == "string" and (filename:lower():match("%.xlsx$") or filename:lower():match("%.xlsm$")) then
		return doc
	end

	return nil
end

local function is_active_xlsx()
	return active_xlsx_doc() ~= nil
end

local function open_output_doc(source_doc, content, suffix)
	local doc = Doc.create((source_doc.filename or "untitled") .. suffix)
	core.workspace_view:open_doc(doc, { word_wrap = false })

	local last_line = #doc.lines
	local last_col = #(doc.lines[last_line] or "") + 1
	doc:remove(1, 1, last_line, last_col)
	doc:insert(1, 1, content)
	doc:set_selection(1, 1)
	doc.save_disabled = true
	doc.save_disabled_reason = "generated from XLSX"
	doc:clean()
end

local function extract(mode)
	local doc = active_xlsx_doc()
	if not doc then
		core.error("XLSX extraction requires an active .xlsx binary viewer")
		return false
	end

	local content, err
	if mode == "markdown" then
		content, err = reader.extract_markdown(doc.filename)
	elseif mode == "tsv" then
		content, err = reader.extract_tsv(doc.filename)
	else
		content, err = reader.extract_text(doc.filename)
	end

	if not content then
		core.error("XLSX extraction failed: %s", tostring(err))
		return false
	end

	local suffix = mode == "markdown" and ".extracted.md"
		or mode == "tsv" and ".extracted.tsv"
		or ".extracted.txt"
	open_output_doc(doc, content, suffix)
	core.log(
		'Extracted "%s" as %s',
		doc.filename,
		mode == "markdown" and "Markdown" or mode == "tsv" and "TSV" or "text"
	)
	return true
end

command.add({
	["xlsx:extract-text"] = {
		requires = { "binary_viewer" },
		predicate = is_active_xlsx,
		perform = function()
			return extract("text")
		end,
	},

	["xlsx:extract-md"] = {
		requires = { "binary_viewer" },
		predicate = is_active_xlsx,
		perform = function()
			return extract("markdown")
		end,
	},

	["xlsx:extract-tsv"] = {
		requires = { "binary_viewer" },
		predicate = is_active_xlsx,
		perform = function()
			return extract("tsv")
		end,
	},
})

return {
	read = reader.read,
	extract_text = reader.extract_text,
	extract_markdown = reader.extract_markdown,
	extract_tsv = reader.extract_tsv,
}
