#' Collection of Local Functions
#'
#' A miscellaneous collection of utility and special purpose functions.
#' 
#' Ideally this package should be installed at start up, which can be done by adding \code{options(defaultPackages = c(getOption("defaultPackages"), "local"))} to \code{.Rprofile}.
#' 
#' Also, this package expects that the path to the intial working directory (home folder) is set in \code{.Rprofile} using the likes of \code{options(home = "/Users/username/R")} (for MacOS, where 'username' is the users login name).
#'
#' For a complete list, use \code{library(help = "local")}.
#'
#' @author Ian Riley \email{ian@riley.asia}
#' @docType package
#' @section Version:
#' \Sexpr{packageVersion("local")}
#' @name local
"_PACKAGE"

self <- "local"
options(installing_package = TRUE)
source('~/.Rprofile')
options(installing_package = NULL)
home_path <- function() ifelse(is.null(options()$home), getwd(), options()$home)
self_path <- file.path(home_path(), paste0(self, "-package"))
self_url <- desc::desc_get_urls(self_path)[1]

#' Document and install self
#'
#' Load required libraries, \code{devtools} and \code{roxygen2}, then document and install this  or specified package.
#' @keywords internal
#' @return Nothing returned.
install_self <- function(package = NULL, path = NULL)
{
	caller <- as.character(match.call())[1] 
	if (is.null(package))
		package <- unlist(strsplit(caller, ':::'))[1]
	if (package == "install_self")
		stop("no package name provided")
	if (is.null(path))
		if (package == self)
	 		path <- self_path
		else {
			package <- gsub("-package$", "", package)
			path <- file.path(home_path(), paste0(package, "-package"))
		}
	
	message(sprintf("'%s' requested installation of '%s' from '%s'", caller, package, path))
	require(devtools)
	require(roxygen2)
	document(path)
	install(path)
	library(package, character.only = TRUE)
}

#' Set working directory to package root
#'
#' @keywords internal
#' @return Current working directory.
pkgdir <- function(package = NULL)
{
	if (is.null(package)) package <- self
	setwd(file.path(home_path(), paste0(package, "-package")))
	message("Working directory set to: ", getwd())
}

isLoaded <- function()
{
	isNamespaceLoaded(self)	
}

local <- isLoaded()
