package controllers

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

// SensorController api
type SensorController struct {
	Ctx     iris.Context
	Service services.SensorService
	Token   Token
}

// Post 创建
// POST /Sensor
func (a *SensorController) Post() {
	ptl := new(models.Sensor)
	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 /sensor
func (a *SensorController) Delete() {
	ptl := new(models.Sensor)
	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 /sensor
func (a *SensorController) Put() {
	ptl := new(models.Sensor)
	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 /sensor/{pid}
func (a *SensorController) GetBy(pid int) {
	p, err := a.Service.GetSensorInfo(uint(pid))
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, p)
}

// Get 获取某个产品的协议列表
// GET /sensor?proid=1&pi&ps&name&label
func (a *SensorController) 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.GetProductSensors(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,
	})
}
