-- lx-bundle:true

--- DOC extraction commands for binary-viewer documents.
-- @module plugins.docutils

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

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

	return nil
end

local function is_active_doc()
	return active_doc_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)

	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 DOC"
	doc:clean()
end

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

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

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

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

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

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

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