package controllers

import (
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/services"

	"github.com/kataras/iris/v12"
)

// DeviceCommandController 设备指令API
type DeviceCommandController struct {
	Ctx     iris.Context
	Service services.DeviceCommandService
	Token   Token
}

// Post 创建设备指令
// POST /device_command
func (a *DeviceCommandController) Post() {
	item := new(models.DeviceCommand)
	if err := parseBody(a.Ctx, item); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	err := a.Service.Create(item)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, item)
}

// Delete 删除设备指令
// DELETE /device_command
func (a *DeviceCommandController) Delete() {
	item := new(models.DeviceCommand)
	if err := parseBody(a.Ctx, item); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	err := a.Service.Delete(item)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "删除成功")
}

// Put 更新设备指令
// PUT /device_command
func (a *DeviceCommandController) Put() {
	item := new(models.DeviceCommand)
	if err := parseBody(a.Ctx, item); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	p, err := a.Service.Update(item)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, p)
}

// Get 根据设备类型id获取指令列表
// GET /device_command?device_type_id=xxx&pi=1&ps=10&name=xxx
func (a *DeviceCommandController) 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
	}
	deviceTypeId := a.Ctx.URLParam("device_type_id")
	name := a.Ctx.URLParam("name")

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

// GetBy 根据id查询设备指令
// GET /device_command/{id}
func (a *DeviceCommandController) GetBy(id string) {
	p, err := a.Service.QueryOne(id)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, p)
}
