package api

import (
	"net/http"

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

// DefaultAPPNode is default app node
const DefaultAPPNode = "general"

// CreateAPP creates app, now just support mysql
func (h *ManagerHandler) CreateAPP(w http.ResponseWriter, r *http.Request) {
	app := new(types.APPConfig)
	if err := readJSON(r.Body, app); err != nil {
		h.rdr.JSON(w, http.StatusOK, util.ErrResponsef("read json body error %v", err))
		return
	}

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

	if app.Labels == nil {
		app.Labels = make(map[string]string)
		app.Labels["node"] = DefaultAPPNode
	}

	err := h.mgr.CreateAPP(app)
	if err != nil {
		h.rdr.JSON(w, http.StatusOK, util.ErrResponsef("create app %+v error %v", app, err))
		return
	}

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

// DeleteAPP deletes app
func (h *ManagerHandler) DeleteAPP(w http.ResponseWriter, r *http.Request) {
	namespace := mux.Vars(r)["namespace"]
	if util.IsEmpty(namespace) {
		h.rdr.JSON(w, http.StatusOK, util.SuccessResponse("namespace empty"))
		return
	}

	name := mux.Vars(r)["name"]
	if util.IsEmpty(name) {
		h.rdr.JSON(w, http.StatusOK, util.SuccessResponse("name empty"))
		return
	}

	err := h.mgr.DeleteAPP(namespace, name)
	if err != nil {
		h.rdr.JSON(w, http.StatusOK, util.ErrResponsef("delete app [namespace:%s] %s error %v", namespace, name, err))
		return
	}

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