-- lx-bundle:true

--- XLS extraction commands for binary-viewer documents.
-- @module plugins.xlsutils

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

local function active_xls_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("%.xls$") then
		return doc
	end

	return nil
end

local function is_active_xls()
	return active_xls_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 XLS"
	doc:clean()
end

local function extract(mode)
	local doc = active_xls_doc()
	if not doc then
		core.error("XLS extraction requires an active .xls 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("XLS 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({
	["xls:extract-text"] = {
		requires = { "binary_viewer" },
		predicate = is_active_xls,
		perform = function()
			return extract("text")
		end,
	},

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

	["xls:extract-tsv"] = {
		requires = { "binary_viewer" },
		predicate = is_active_xls,
		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,
}
