package api

import (
	"net/http"

	"github.com/gorilla/mux"
	"github.com/pingcap/schrodinger/pkg/types"
	"github.com/pingcap/schrodinger/util"
)

// SetFailpoint sets failpoint from storage
func (h *ManagerHandler) SetFailpoint(w http.ResponseWriter, r *http.Request) {
	failpoint := new(types.Failpoint)
	if err := readJSON(r.Body, failpoint); err != nil {
		h.rdr.JSON(w, http.StatusOK, util.ErrResponsef("read json body %v", err))
		return
	}

	if err := failpoint.Verify(); err != nil {
		h.rdr.JSON(w, http.StatusOK, util.ErrResponsef("verify failpoint %+v error %v", failpoint, err))
		return
	}

	if err := h.mgr.SetFailpoint(failpoint); err != nil {
		h.rdr.JSON(w, http.StatusOK, util.ErrResponsef("set failpoint %+v error %v", failpoint, err))
		return
	}
	h.rdr.JSON(w, http.StatusOK, util.SuccessResponse("ok"))
}

// GetFailpoint returns failpoint accoroding to name
func (h *ManagerHandler) GetFailpoint(w http.ResponseWriter, r *http.Request) {
	name := mux.Vars(r)["name"]
	fp, err := h.mgr.GetFailpoint(name)
	if err != nil {
		h.rdr.JSON(w, http.StatusOK, util.ErrResponsef("get failpoint %s error %v", name, err))
		return
	}

	h.rdr.JSON(w, http.StatusOK, util.SuccessResponse(fp))
}

// ListFailpoints returns all failpoints
func (h *ManagerHandler) ListFailpoints(w http.ResponseWriter, r *http.Request) {
	fps := h.mgr.ListFailpoints()

	size := getSize(r)
	offset := getOffset(r)
	start, end := getPagingIndexes(int64(len(fps)), offset, size)

	listData := ListData{
		List:   fps[start:end],
		Offset: offset,
		Size:   size,
		Total:  int64(len(fps)),
	}
	h.rdr.JSON(w, http.StatusOK, util.SuccessResponse(listData))
}
