package inbox

import (
	"fmt"
	"net/http"

	"git.kirsle.net/apps/gosocial/pkg/models"
	"git.kirsle.net/apps/gosocial/pkg/session"
	"git.kirsle.net/apps/gosocial/pkg/templates"
)

// Compose a new chat coming from a user's profile page.
func Compose() http.HandlerFunc {
	tmpl := templates.Must("inbox/compose.html")
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// To whom?
		username := r.FormValue("to")
		user, err := models.FindUser(username)
		if err != nil {
			templates.NotFoundPage(w, r)
			return
		}

		currentUser, err := session.CurrentUser(r)
		if err != nil {
			session.FlashError(w, r, "Unexpected error: could not get currentUser.")
			templates.Redirect(w, "/")
			return
		}

		if currentUser.ID == user.ID {
			session.FlashError(w, r, "You cannot send a message to yourself.")
			templates.Redirect(w, "/messages")
			return
		}

		// Any blocking?
		if models.IsBlocking(currentUser.ID, user.ID) && !currentUser.IsAdmin {
			session.FlashError(w, r, "You are blocked from sending a message to this user.")
			templates.Redirect(w, "/messages")
			return
		}

		// POSTing?
		if r.Method == http.MethodPost {
			var (
				message = r.FormValue("message")
				from    = r.FormValue("from") // e.g. "inbox", default "profile", where to redirect to
			)
			if len(message) == 0 {
				session.FlashError(w, r, "A message is required.")
				templates.Redirect(w, r.URL.Path+"?to="+username)
				return
			}

			// Post it!
			m, err := models.SendMessage(currentUser.ID, user.ID, message)
			if err != nil {
				session.FlashError(w, r, "Failed to create the message in the database: %s", err)
				templates.Redirect(w, r.URL.Path+"?to="+username)
				return
			}

			session.Flash(w, r, "Your message has been delivered!")
			if from == "inbox" {
				templates.Redirect(w, fmt.Sprintf("/messages/read/%d", m.ID))
			}
			templates.Redirect(w, "/messages")
			return
		}

		var vars = map[string]interface{}{
			"User": user,
		}
		if err := tmpl.Execute(w, r, vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})
}
