package controllers

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

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

// DeviceStatusController 设备状态API
type DeviceStatusController struct {
	Ctx     iris.Context
	Service services.DeviceStatusService
	Token   Token
}

// Post 创建设备状态
// POST /device_status
func (a *DeviceStatusController) Post() {
	item := new(models.DeviceStatus)
	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_status
func (a *DeviceStatusController) Delete() {
	item := new(models.DeviceStatus)
	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_status
func (a *DeviceStatusController) Put() {
	item := new(models.DeviceStatus)
	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_status?device_type_id=xxx&pi=1&ps=10&name=xxx
func (a *DeviceStatusController) 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_status/{id}
func (a *DeviceStatusController) GetBy(id string) {
	p, err := a.Service.QueryOne(id)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, p)
}
