package controllers

import (
	"github.com/kataras/iris/v12"
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/services"
)

// RuleChainController api
type RuleChainController struct {
	Ctx     iris.Context
	Service services.RuleChainService
	Token   Token
}

// Post post
// POST /admin/rule_chain
func (a *RuleChainController) Post() {
	ptl := new(models.RuleChain)
	if err := parseBody(a.Ctx, ptl); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ptl.VendorID = a.Token.getVendorID(a.Ctx)
	err := a.Service.Create(ptl)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, ptl)
}

// Delete delete
// DELETE /admin/rule_chain
func (a *RuleChainController) Delete() {
	RuleChain := new(models.RuleChain)
	if err := parseBody(a.Ctx, RuleChain); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Delete(RuleChain); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, RuleChain)
}

// Put 更新
// PUT /admin/rule_chain
func (a *RuleChainController) Put() {
	params := new(models.RuleChainParams)
	if err := parseBody(a.Ctx, params); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Update(params); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "已保存")
}

// Get get RuleChains
// GET /admin/rule_chain?pi=&ps=&name=
func (a *RuleChainController) Get() {
	pi, err := a.Ctx.URLParamInt("pi")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ps, err := a.Ctx.URLParamInt("ps")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	name := a.Ctx.URLParam("name")
	vendorId := a.Token.getVendorID(a.Ctx)
	datas, total, err := a.Service.Query(pi, ps, name, vendorId)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}

	done(a.Ctx, map[string]interface{}{
		"list":  datas,
		"total": total,
	})
}

// PutChange 更新
// PutChange /rule_chain/change
func (a *RuleChainController) PutChange() {
	params := new(models.ChangeRootParams)
	if err := parseBody(a.Ctx, params); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if params.VendorId == "" {
		params.VendorId = a.Token.getVendorID(a.Ctx)
	}

	err := a.Service.UpdateChainRoot(params)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "已更新")
}
