package handler

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

func (h *Handler) saveStatus(w http.ResponseWriter, r *http.Request) {
	user, err := h.getUser(r)
	if err != nil {
		unauthorized(w, r)
		return
	}
	f := form.NewStatusForm(r)
	status := model.Status{
		User:    user,
		Content: f.Content,
		Face:    f.Face,
                Number: f.Number,
	}
	if err := status.Validate(); err != nil {
		f.Error = err.Error()
		h.renderLayout(w, "create_status", map[string]interface{}{
			"form": f,
		}, "")
		return
	}
	if err := h.storage.CreateStatus(status); err != nil {
		serverError(w, err)
		return
	}
	if r.URL.Query().Get("silent") != "1" {
		session, err := h.sess.Store.Get(r, "status")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		session.AddFlash("Status updated!")
		err = session.Save(r, w)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/", http.StatusFound)
	}
}
