package server

import (
	"fmt"
	"github.com/gorilla/mux"
	"html/template"
	"io/ioutil"
	"path/filepath"
	"strings"
)

var tPath = "./web/tpl/"
var dPath = "./web/data/"

var templateDirs = []string{"./web/tpl", "./web/data"}
var templates *template.Template

func getTemplates() (templates *template.Template, err error) {
	var allFiles []string
	for _, dir := range templateDirs {
		files2, _ := ioutil.ReadDir(dir)
		for _, file := range files2 {
			filename := file.Name()
			if strings.HasSuffix(filename, ".html") {
				filePath := filepath.Join(dir, filename)
				fmt.Println("Template found: ", filePath)
				allFiles = append(allFiles, filePath)
			}
		}
	}

	templates, err = template.New("").ParseFiles(allFiles...)
	return
}

func init() {
	templates, _ = getTemplates()
}

func CreateRoutes() *mux.Router {
	r := mux.NewRouter()
	r.HandleFunc("/dan/{date}", dailyArticlesHandler)
	r.HandleFunc("/{id:[0-9]+}/{slug}", articleHandler)
	r.HandleFunc("/", rootHandler)
	return r
}
