package handler

import (
	"fmt"
	"net/http"
	"status/web/handler/form"
)

func (h *Handler) updateSettings(w http.ResponseWriter, r *http.Request) {
	user, err := h.getUser(r)
	if err != nil {
		unauthorized(w, r)
		return
	}
	f := form.NewSettingsForm(r)
	if err := f.Validate(); err != nil {
		serverError(w, err)
		return
	}
	if err := h.storage.UpdateSettings(user, f.Homepage, f.About, f.Picture, f.Email); err != nil {
		serverError(w, err)
		return
	}
	session, err := h.sess.Store.Get(r, "status")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	session.AddFlash("Settings updated!")
	err = session.Save(r, w)
	http.Redirect(w, r, fmt.Sprintf("/settings"), http.StatusFound)
}
