package handler

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

func (h *Handler) handleRemoveStatus(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
	}
	switch r.Method {
	case "GET":
		h.renderLayout(w, "confirm_remove_status", map[string]interface{}{
			"status":         status,
			csrf.TemplateTag: csrf.TemplateField(r),
		}, user)
	case "POST":
		err = h.storage.DeleteStatus(status.Id, user)
		if 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 successfully removed!")
		err = session.Save(r, w)
		http.Redirect(w, r, "/manage", http.StatusFound)
	}
}
