package fs

import (
	"text/template"

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

// NexFileHandler builds a handler which serves up files from a file system.
//
// It only serves responses for paths which correspond to files, not directories.
func NexFileHandler(fsroot, urlroot string) sr.Handler {
	return fileHandler(nex.ServerProtocol, fsroot, urlroot)
}

// NexDirectoryDefault serves up default files for directory path requests.
//
// If any of the supported filenames are found in the requested directory, the
// contents of that file is returned as the nex response.
//
// It returns nil for any paths which don't correspond to a directory.
func NexDirectoryDefault(fsroot, urlroot string, filenames ...string) sr.Handler {
	return directoryDefault(nex.ServerProtocol, fsroot, urlroot, false, filenames...)
}

// NexDirectoryListing 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 returns
// a nil response. Trailing slashes are necessary for relative links to work properly.
//
// The template may be nil, in which case DefaultNexDirectoryList is used instead. The
// template is then processed with RenderDirectoryListing.
func NexDirectoryListing(fsroot, urlroot string, tmpl *template.Template) sr.Handler {
	if tmpl == nil {
		tmpl = DefaultNexDirectoryList
	}
	return directoryListing(nex.ServerProtocol, fsroot, urlroot, "", false, tmpl)
}

var DefaultNexDirectoryList = template.Must(template.New("nex_dirlist").Parse(`
{{ .DirName }} directory:
{{ range .Entries }}
=> ./{{ .Name }}{{ if .IsDir }}/{{ end -}}
{{ end }}
`[1:]))