package fs

import (
	"text/template"

	sr "tildegit.org/tjp/sliderule"
	"tildegit.org/tjp/sliderule/spartan"
)

// SpartanFileHandler builds a handler which serves up files from a root directory.
//
// It only serves responses for paths which correspond to regular files or symlinks to them.
func SpartanFileHandler(fsroot, urlroot string) sr.Handler {
	return fileHandler(spartan.ServerProtocol, fsroot, urlroot)
}

// SpartanDirectoryDefault serves up default files for directory path requests.
//
// If any of the supported filenames are found, the contents of the file is returned as the
// spartan response.
//
// It returns nil for any paths which don't correspond to a directory.
//
// When it encounters a directory path which doesn't end in a trailing slash (/) it
// redirects to the URL with the slash appended. This is necessary for relative links
// in the directory's contents to function properly.
func SpartanDirectoryDefault(fsroot, urlroot string, filenames ...string) sr.Handler {
	return directoryDefault(spartan.ServerProtocol, fsroot, urlroot, true, filenames...)
}

// SpartanDirectoryListing produces a listing of the contents of any requested directories.
//
// It returns a nil response for any paths which don't correspond to a filesystem directory.
//
// When it encounters a directory path which doesn't end in a trailing slash (/) it
// redirects to a URL with the trailing slash appended. This is necessary for relative
// links not the directory's contents to function properly.
//
// The template may be nil, in which case DefaultSpartanDirectoryList is used instead. The
// template is then processed with RenderDirectoryListing.
func SpartanDirectoryListing(fsroot, urlroot string, tmpl *template.Template) sr.Handler {
	if tmpl == nil {
		tmpl = DefaultSpartanDirectoryList
	}
	return directoryListing(spartan.ServerProtocol, fsroot, urlroot, "file.gmi", true, tmpl)
}

// DefaultSpartanDirectoryList is a tmeplate which renders a reasonable gemtext dir listing.
var DefaultSpartanDirectoryList = DefaultGeminiDirectoryList