package controllers

import (
	"fmt"
	"html/template"
	"net/http"

	"git.kirsle.net/apps/gophertype/pkg/mail"
	"git.kirsle.net/apps/gophertype/pkg/markdown"
	"git.kirsle.net/apps/gophertype/pkg/responses"
	"git.kirsle.net/apps/gophertype/pkg/session"
	"git.kirsle.net/apps/gophertype/pkg/settings"
	"github.com/albrow/forms"
)

// ContactHandler receives admin emails from users.
func ContactHandler(w http.ResponseWriter, r *http.Request) {
	var (
		v   = responses.NewTemplateVars(w, r)
		ses = session.Get(r)
	)

	// Load their cached name from any previous comments they may have posted.
	name := ses.Name
	email := ses.Email

	for r.Method == http.MethodPost {
		// Validate form parameters.
		form, _ := forms.Parse(r)
		val := form.Validator()
		val.Require("message")
		if val.HasErrors() {
			v.ValidationError = val.ErrorMap()
			v.V["Error"] = "Missing required form fields."
			break
		}

		var (
			name    = form.Get("name")
			email   = form.Get("email")
			subject = form.Get("subject")
			message = form.Get("message")
		)

		// Cache their name in their session for future comments/asks.
		ses.Name = name
		ses.Email = email
		ses.Save(w)

		// Email the site admin.
		if name == "" {
			name = "Anonymous"
		}
		if subject == "" {
			subject = "No Subject"
		}

		go mail.EmailAdmins(mail.Email{
			Subject:  fmt.Sprintf("Contact Me (%s) from %s: %s", settings.Current.Title, name, subject),
			Template: "_builtin/email/generic.gohtml",
			Data: map[string]interface{}{
				"Subject": subject,
				"ReplyTo": email,
				"Message": template.HTML(
					markdown.RenderMarkdown(fmt.Sprintf(
						"Subject: %s\nSender name: %s\nSender email: %s\n\n%s\n",
						subject, name, email, message,
					)),
				),
			},
		})

		session.Flash(w, r, "Thank you! Your message has been e-mailed to the site owner.")
		responses.Redirect(w, r, "/contact")
		return
	}

	v.V["name"] = name
	v.V["email"] = email
	responses.RenderTemplate(w, r, "_builtin/contact.gohtml", v)
}
