/*
Copyright 2017-2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package handlers

import (
	"bytes"
	"fmt"
	"html/template"
	"io/fs"
	"net/http"
	"path/filepath"
	"strings"

	"github.com/Masterminds/sprig/v3"

	"git.cacert.org/cacert-boardvoting/internal/forms"
	"git.cacert.org/cacert-boardvoting/internal/models"
	"git.cacert.org/cacert-boardvoting/ui"
)

func checkRole(v *models.User, roles ...models.RoleName) (bool, error) {
	hasRole, err := v.HasRole(roles...)
	if err != nil {
		return false, fmt.Errorf("could not determine user roles: %w", err)
	}

	return hasRole, nil
}

type TemplateData struct {
	PrevPage     string
	NextPage     string
	Motion       *models.Motion
	Motions      []*models.Motion
	User         *models.User
	Users        []*models.User
	Request      *http.Request
	Flashes      []FlashMessage
	Form         forms.Form
	ActiveNav    topLevelNavItem
	ActiveSubNav subLevelNavItem
	CSRFToken    string
}

type TemplateCache struct {
	cache map[string]*template.Template
}

func NewTemplateCache() (*TemplateCache, error) {
	cache := map[string]*template.Template{}

	pages, err := fs.Glob(ui.Files, "html/pages/*.html")
	if err != nil {
		return nil, fmt.Errorf("could not find page templates: %w", err)
	}

	funcMaps := sprig.FuncMap()
	funcMaps["nl2br"] = func(text string) template.HTML {
		// #nosec G203 input is sanitized
		return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "<br>"))
	}
	funcMaps["canManageUsers"] = func(v *models.User) (bool, error) {
		return checkRole(v, models.RoleSecretary, models.RoleAdmin)
	}
	funcMaps["canVote"] = func(v *models.User) (bool, error) {
		return checkRole(v, models.RoleVoter)
	}
	funcMaps["canStartVote"] = func(v *models.User) (bool, error) {
		return checkRole(v, models.RoleVoter)
	}

	for _, page := range pages {
		name := filepath.Base(page)

		ts, err := template.New("").Funcs(funcMaps).ParseFS(
			ui.Files,
			"html/base.html",
			"html/partials/*.html",
			page,
		)
		if err != nil {
			return nil, fmt.Errorf("could not parse base template: %w", err)
		}

		cache[name] = ts
	}

	return &TemplateCache{cache: cache}, nil
}

func (c *TemplateCache) render(w http.ResponseWriter, status int, page string, data *TemplateData) {
	ts, ok := c.cache[page]
	if !ok {
		panic(fmt.Sprintf("the template %s does not exist", page))
	}

	buf := new(bytes.Buffer)

	err := ts.ExecuteTemplate(buf, "base", data)
	if err != nil {
		panic(err)
	}

	w.WriteHeader(status)

	_, _ = buf.WriteTo(w)
}
