package handler

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

func (h *Handler) updateStatus(w http.ResponseWriter, r *http.Request) {
	user, err := h.getUser(r)
	if err != nil {
		unauthorized(w, r)
		return
	}
	id, err := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
	if err != nil {
		serverError(w, err)
		return
	}
	status, err := h.storage.StatusById(id)
	if err != nil {
		serverError(w, err)
		return
	}

	if user != status.User {
		unauthorized(w, r)
		return
	}
	f := form.NewStatusForm(r)
	status.Content = f.Content
	status.Face = f.Face
	if err := status.Validate(); err != nil {
		f.Error = err.Error()
		h.renderLayout(w, "edit_post", map[string]interface{}{
			"form": f,
		}, "")
		return
	}
	if err := h.storage.UpdateStatus(status); 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("Status edited!")
	err = session.Save(r, w)
	http.Redirect(w, r, fmt.Sprintf("/edit?id=%d", status.Id), http.StatusFound)
}
