package webui

import (
	"net/http"
	"strings"
)

// webmailSignaturesPage lists a mailbox's saved signatures — add/edit happens in a
// popup (webmail_settings_chrome.html's signature modal), not on this page itself.
func (a *App) webmailSignaturesPage(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	signatures, err := a.DB.ListSignatures(mbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading signatures")
	}
	aliasDefaults, err := a.DB.ListSignatureAliasDefaults(mbox.ID)
	if err != nil {
		setFlash(w, "error", "Error loading alias defaults")
	}

	a.render(w, r, "webmail_signatures.html", M{
		"mailbox": mbox, "signatures": signatures, "send_as_options": a.sendAsAddresses(mbox),
		"alias_defaults": aliasDefaults,
		"flashes":        popFlashes(w, r), "active_section": "signatures",
	})
}

// webmailSignatureSave creates a new signature, or updates one when id (a hidden
// form field, not a path segment — this is a single form reused for add and edit) is
// set. default_for_email/default_new/default_reply (all optional) additionally set
// this signature as a specific send-as alias's default — see
// db.SetSignatureAliasDefault. The mailbox's own primary-address default is set
// separately, via the existing per-row "Use for new"/"Use for reply/forward" buttons
// (webmailSignatureSetDefault) — deliberately not folded into this form, since that
// control already works and scoping it here would just be two ways to do the same
// thing for that one address.
func (a *App) webmailSignatureSave(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	if err := r.ParseForm(); err != nil {
		setFlash(w, "error", "Invalid form data")
		http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
		return
	}
	name := strings.TrimSpace(r.FormValue("name"))
	contentHTML := r.FormValue("content_html")
	if name == "" {
		setFlash(w, "error", "Give the signature a name")
		http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
		return
	}

	id := int64(atoi(r.FormValue("id")))
	var err error
	if id != 0 {
		err = a.DB.UpdateSignature(mbox.ID, id, name, contentHTML)
	} else {
		id, err = a.DB.CreateSignature(mbox.ID, name, contentHTML)
	}
	if err != nil {
		a.Logger.Error("save signature for mailbox %d: %v", mbox.ID, err)
		setFlash(w, "error", "Could not save the signature")
		http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
		return
	}

	if forEmail := strings.TrimSpace(r.FormValue("default_for_email")); forEmail != "" {
		if r.FormValue("default_new") != "" {
			a.DB.SetSignatureAliasDefault(mbox.ID, id, forEmail, false)
		}
		if r.FormValue("default_reply") != "" {
			a.DB.SetSignatureAliasDefault(mbox.ID, id, forEmail, true)
		}
	}

	setFlash(w, "success", "Signature saved")
	http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
}

func (a *App) webmailSignatureDelete(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	id := int64(atoi(r.PathValue("id")))
	if err := a.DB.DeleteSignature(mbox.ID, id); err != nil {
		setFlash(w, "error", "Could not delete the signature")
	} else {
		setFlash(w, "success", "Signature deleted")
	}
	http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
}

// webmailSignatureSetDefault marks a signature (or, when id=0, clears the flag
// entirely) as the mailbox's default for new messages or for reply/forward, per the
// "which" form field ("new" or "reply"). This is the mailbox's own primary-address
// default — see webmailSignatureSetAliasDefault for a specific send-as alias's.
func (a *App) webmailSignatureSetDefault(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	id := int64(atoi(r.PathValue("id")))
	forReply := r.URL.Query().Get("which") == "reply"
	if err := a.DB.SetDefaultSignature(mbox.ID, id, forReply); err != nil {
		setFlash(w, "error", "Could not update the default signature")
	} else {
		setFlash(w, "success", "Default signature updated")
	}
	http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
}

// webmailSignatureRemoveAliasDefault clears one alias's default-for-new or
// default-for-reply override (the little x on a signature's alias-scoped badge),
// falling back to the mailbox's own primary default for that alias again.
func (a *App) webmailSignatureRemoveAliasDefault(w http.ResponseWriter, r *http.Request) {
	mbox := mailboxFromContext(r)
	if err := r.ParseForm(); err != nil {
		setFlash(w, "error", "Invalid form data")
		http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
		return
	}
	forEmail := strings.TrimSpace(r.FormValue("for_email"))
	forReply := r.FormValue("for_reply") != ""
	if err := a.DB.ClearSignatureAliasDefault(mbox.ID, forEmail, forReply); err != nil {
		setFlash(w, "error", "Could not remove the alias default")
	} else {
		setFlash(w, "success", "Alias default removed")
	}
	http.Redirect(w, r, MailboxPrefix+"/signatures", http.StatusFound)
}
