package controllers

import (
	"encoding/json"

	oclib "cloud.o-forge.io/core/oc-lib"
	"cloud.o-forge.io/core/oc-lib/models/peer"
	beego "github.com/beego/beego/v2/server/web"
)

// Operations about workflow
type PeerController struct {
	beego.Controller
}

// @Title Search
// @Description search workspace
// @Param	search		path 	string	true		"the word search you want to get"
// @Success 200 {workspace} models.workspace
// @router /search/:search [get]
func (o *PeerController) Search() {
	// store and return Id or post with UUIDLibDataEnum
	search := o.Ctx.Input.Param(":search")
	o.Data["json"] = oclib.Search(nil, search, oclib.LibDataEnum(oclib.PEER))
	o.ServeJSON()
}

// @Title Update
// @Description create peers
// @Param	id		path 	string	true		"the peer id you want to get"
// @Param	body		body 	models.peer	true		"The peer content"
// @Success 200 {object} models.peer
// @router /:id [put]
func (o *PeerController) Put() {
	// store and return Id or post with UUID
	var res map[string]interface{}
	id := o.Ctx.Input.Param(":id")
	json.Unmarshal(o.Ctx.Input.CopyBody(10000), &res)
	data := oclib.UpdateOne(oclib.LibDataEnum(oclib.PEER), res, id, nil)
	o.Data["json"] = data
	o.ServeJSON()
}

// @Title GetAll
// @Description find all peer
// @Success 200 {peer} models.peer
// @router / [get]
func (o *PeerController) GetAll() {
	o.Data["json"] = oclib.LoadAll(oclib.LibDataEnum(oclib.PEER))
	o.ServeJSON()
}

// @Title Get
// @Description find peer by peerid
// @Param	id		path 	string	true		"the peer id you want to get"
// @Success 200 {peer} models.peer
// @router /:id [get]
func (o *PeerController) Get() {
	id := o.Ctx.Input.Param(":id")
	o.Data["json"] = oclib.LoadOne(oclib.LibDataEnum(oclib.PEER), id)
	o.ServeJSON()
}

// @Title Partner
// @Description add partner peer by peerid
// @Param	id		path 	string	true		"the peer id you want to partner"
// @Success 200 {peer} models.peer
// @router /:id/partner [post]
func (o *PeerController) Partner() {
	id := o.Ctx.Input.Param(":id")
	o.Data["json"] = oclib.UpdateOne(oclib.LibDataEnum(oclib.PEER), map[string]interface{}{
		"state": peer.PARTNER,
	}, id)
	o.ServeJSON()
}

// @Title Blacklist
// @Description add blacklist peer by peerid
// @Param	id		path 	string	true		"the peer id you want to blacklist"
// @Success 200 {peer} models.peer
// @router /:id/blacklist [post]
func (o *PeerController) Blacklist() {
	id := o.Ctx.Input.Param(":id")
	o.Data["json"] = oclib.UpdateOne(oclib.LibDataEnum(oclib.PEER), map[string]interface{}{
		"state": peer.BLACKLIST,
	}, id)
	o.ServeJSON()
}

// @Title DeleteState
// @Description delete state peer by peerid
// @Param	id		path 	string	true		"the peer id you want to delete state"
// @Success 200 {peer} models.peer
// @router /:id/undo_state [post]
func (o *PeerController) DeleteState() {
	id := o.Ctx.Input.Param(":id")
	o.Data["json"] = oclib.UpdateOne(oclib.LibDataEnum(oclib.PEER), map[string]interface{}{
		"state": peer.NONE,
	}, id)
	o.ServeJSON()
}