#' Document Package Using Specified Format
#'
#' Create documentation of packages in text, HTML, Latex, PDF and MoinMoin fomrats using Rd converters from "tools" package and \special{MoinMoin} converter from this package. With \special{MoinMoin} it is possible to convert either a single Rd file (using Rd2moin as a substitute for the converters provided by "tools"), or all Rd files in the package to a combined \special{MoinMoin} page.
#' @param Rd a filename or an Rd object for single Rd file conversion. For package conversion, either an installed package name or a path to package top level directory. Default is working directory.
#' @param type charcter: indicating the selected format. The options are, "text", "html", "latex", "example" (extract R code in the examples), "pdf" and "moin". The default is set to "unknown" so this parameter must be specified.
#' @param ... additional paramaters to pass to the converter. See \code{\link[tools:Rd2HTML]{Rd2HTML}}, \code{\link[rhelium:Rd2moin]{Rd2moin}} and/or \code{\link[rhelium:moinDoc]{moinDoc}} for futher details.
#' @author Ian Riley \email{ian@@riley.asia}
#' @return Fomrated documentation for single or multiple Rd files for R package.
#' @examples
#' pkgDoc("~/R projects/rhelium-package")
#' @export
pkgDoc <- function(Rd = '.', type = "unknown", ...)
{	
	if(is.null(Rd) || is.na(Rd) || Rd == "") stop('argument "Rd" is missing, with no default')
	
	switch(class(Rd),
		"Rd" = {}, # OK so do nothing
		"character" = {
			if (!is.installed(Rd) && !is.Rd_file(Rd) && !has.Rd_man(Rd))
				stop('argument "Rd" is not an Rd folder/file, installed package or package base with "man" folder containing Rd files')
		},
		stop('class "', class(Rd), '" is not sutable for argument "Rd"')
		)

	# until functionality added for types other than "moin" and "pdf"
	if (!type %in% c("moin", "pdf") && !(is.Rd(Rd) || is.Rd_file(Rd)))
		stop('type "', type, '" only accepts an Rd object or file')

	switch(type,
		"text"		= Rd2txt(Rd, ...),
		"html"		= Rd2HTML(Rd, ...),
		"latex"		= Rd2latex(Rd, ...),
		"example"	= Rd2ex(Rd, ...),
		"moin"		= ifelse((is.Rd(Rd) || is.Rd_file(Rd)),
			Rd2moin(Rd, ...), 
			moinDoc(Rd, ...)),
		"pdf"		= .Rd2pdf(Rd),
		"unknown" = stop("no 'type' specified", call. = FALSE),
		stop('"type" must be one of "text", "html", "latex", "example" or "moin"')
        )
    invisible()
}

#some helper functions
	
RdDir <- function(x) dir(x, ".Rd$")

# tests
is.Rd <- function(x) (class(x) == "Rd")

is.Rd_file <- function(x) (file.exists(x) && file_ext(x) == "Rd")

is.Rd_db <- function(x) (all(vapply(x, is.Rd, logical(1))))

has.Rd_man <- function(x) {
	x <- suppressWarnings(normalizePath(file.path(x, "/man")))
	(dir.exists(x) && 
		any(vapply(normalizePath(file.path(x, RdDir(x))), is.Rd_file, logical(1))))
}

RDir <- function(x) dir(x, ".R$")

is.R_file <- function(x) (file.exists(x) && file_ext(x) == "R")

get.R_files <- function (x) RDir(normalizePath(file.path(x, "/R")))

has.R_code <- function(x) {
	x <- suppressWarnings(normalizePath(file.path(x, "/R")))
	(dir.exists(x) && 
		any(vapply(normalizePath(file.path(x, RDir(x))), is.R_file, logical(1))))
}

is.installed <- function(x) (length(path.package(x, quiet = TRUE)) > 0)

installed.path <- function(x) path.package(x, quiet = TRUE)[1]

.Rd2pdf = function(Rd) {
	# wrapper for R CMD Rd2pdf files
	if (is.Rd(Rd)) {
		name <- paste0(x[[grep("\\\\name", RdTags(x))]])
		tempFile <- "./_Rd2pdf.Rd"
		out <- file(tempFile, open= "wt")
		writeLines(paste0(Rd, collapse = ""), out)
		close(out)
		on.exit(if (file.exists(tempFile)) file.remove(tempFile), add = TRUE)
		args <- sprintf('--title="%s" --output="./%s.pdf" %s', name, name, tempFile)
		} 
	else if (is.Rd_file(Rd)) args <- Rd
	else if (!is.installed(Rd) && has.Rd_man(Rd)) { # local takes priority over installed
		args <- sprintf('--output="%s/%s.pdf" %s', Rd, Rd, Rd)
		}
	else args <- sprintf('--output="./%s.pdf" %s', Rd, installed.path(Rd))
	
	err <- tools::Rcmd(paste("Rd2pdf --batch --no-preview --force", args),
		stderr = "Rd2pdf.log")
	
	if (err) stop("Processing error occurred: check log file in working directory")
	else if (file.exists("Rd2pdf.log")) file.remove("Rd2pdf.log")
}

