package controllers

import (
	"sws_xcx/enums"
	"sws_xcx/service"
	"sws_xcx/utils"
)

type DeviceApiController struct {
	BaseApiAuthController
}

// @Title GetMyDevices
// @Description 获取绑定的设备列表
// @Success 200 {array} models.Device success
// @Failure 500 error
// @Security token
// @router /getmydevices [get]
func (c *DeviceApiController) GetMyDevices() {

	devices, err := service.NewDeviceService().GetMyDevices(c.CurrentUser.Id)
	if err != nil {
		c.ServeDynamicFailJsonSend(err.Error())
		return
	}
	c.ServeSuccessJSON(devices)

}

// @Title GetDeviceDetail
// @Description 根据设备ID获取设备详细信息
// @Param   deviceid query int true "设备ID"
// @Success 200 {object} models.Device success
// @Failure 500 error
// @Security token
// @router /getdevicedetail [get]
func (c *DeviceApiController) GetDeviceDetail() {

	utils.TraceLog(c.GetString("deviceid"))
	id, err := c.GetInt("deviceid")
	if err != nil {
		c.ServeDynamicFailJsonSend(err.Error())
		return
	}
	device, err := service.NewDeviceService().GetDeviceInfo(id)
	if err != nil {
		c.ServeDynamicFailJsonSend(err.Error())
		return
	}
	c.ServeSuccessJSON(device)
}

// @Title BindDevice
// @Description 通过扫码绑定设备
// @Param   qrcode query string true "设备二维码"
// @Success 200  success
// @Failure 500 error
// @Security token
// @router /binddevice [post]
func (c *DeviceApiController) BindDevice() {
	qrcode := c.GetString("qrcode")
	if err := service.NewDeviceService().BindDevice(c.CurrentUser.Id, qrcode); err != nil {
		c.ServeDynamicFailJsonSend(err.Error())
		return
	}
	c.ServeSuccessJSON(new(interface{}))
}

// @Title BindDevice
// @Description 通过设备ID绑定设备
// @Param   deviceId query string true "设备ID"
// @Success 200  success
// @Failure 500 error
// @Security token
// @router /binddevicebyid [post]
func (c *DeviceApiController) BindDeviceById() {
	deviceId, err := c.GetUint64("deviceId")
	if err != nil || deviceId == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
		return
	}
	if err := service.NewDeviceService().BindDeviceById(c.CurrentUser.Id, deviceId); err != nil {
		c.ServeDynamicFailJsonSend(err.Error())
		return
	}
	c.ServeSuccessJSON(new(interface{}))
}

// @Title UnBindDevice
// @Description 解绑设备
// @Param   deviceid query int true "设备ID"
// @Success 200  success
// @Failure 500 error
// @Security token
// @router /unbinddevice [post]
func (c *DeviceApiController) UnbindDevice() {
	id, err := c.GetInt("deviceid")
	if err != nil {
		c.ServeDynamicFailJsonSend(err.Error())
		return
	}
	if err := service.NewDeviceService().UnbindDevice(c.CurrentUser.Id, uint64(id)); err != nil {
		c.ServeDynamicFailJsonSend(err.Error())
		return
	}
	c.ServeSuccessJSON(new(interface{}))
}
