package controllers

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

// ProtocalController api
type ProtocalController struct {
	Ctx     iris.Context
	Service services.ProtocalService
	Token   Token
}

// Post 创建
// POST /protocal
func (a *ProtocalController) Post() {
	ptl := new(models.Protocal)
	if err := parseBody(a.Ctx, ptl); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	err := a.Service.Create(ptl)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, ptl)
}

// Delete 删除
// DELETE /protocal
func (a *ProtocalController) Delete() {
	ptl := new(models.Protocal)
	if err := parseBody(a.Ctx, ptl); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	err := a.Service.Delete(ptl)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "删除成功")
}

// Put 更新
// PUT /protocal
func (a *ProtocalController) Put() {
	ptl := new(models.Protocal)
	if err := parseBody(a.Ctx, ptl); err != nil {
		badRequest(a.Ctx, err)
		return
	}

	p, err := a.Service.Update(ptl)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, p)
}

// GetBy 根据id查询协议的内容
// GET /protocal/{pid}
func (a *ProtocalController) GetBy(pid int) {
	p, err := a.Service.GetProtocalInfo(uint(pid))
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, p)
}

// Get 获取某个产品的协议列表
// GET /protocal?proid=1&pi&ps&name&label
func (a *ProtocalController) 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
	}
	proid, err := a.Ctx.URLParamInt("proid")
	name := a.Ctx.URLParam("name")
	label := a.Ctx.URLParam("label")

	ds, total, err := a.Service.GetProductProtocals(uint(proid), pi, ps, name, label)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"list":  ds,
		"total": total,
	})
}
