package handler

import (
	"github.com/gorilla/csrf"
	"github.com/gorilla/mux"
	"net/http"
	"strconv"
)

func RouteInt64Param(r *http.Request, param string) int64 {
	vars := mux.Vars(r)
	value, err := strconv.ParseInt(vars[param], 10, 64)
	if err != nil {
		return 0
	}
	if value < 0 {
		return 0
	}
	return value
}

func (h *Handler) showEditStatusView(w http.ResponseWriter, r *http.Request) {
	protectClickJacking(w)
	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
	}
	session, err := h.sess.Store.Get(r, "status")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	flash := ""
	if flashes := session.Flashes(); len(flashes) > 0 {
		flash = flashes[0].(string)
	}
	session.Save(r, w)
	h.renderLayout(w, "edit_status", map[string]interface{}{
		"status":         status,
		"flash":          flash,
		csrf.TemplateTag: csrf.TemplateField(r),
	}, user)
}
