package device

import (
	"Wine-Server/utils"
	"Wine-Server/utils/tables"
	"github.com/gorilla/websocket"
)

func QueryManager(conn *websocket.Conn, manager *tables.ManagerTable, data any) {
	if !manager.Super {
		_ = conn.WriteJSON(utils.WsError("auth failed."))
		return
	}
	name, _ := data.(string)
	res, err := tables.ManagerQuery(name)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsError("query manager failed"))
		return
	}
	_ = conn.WriteJSON(utils.WsEvent("superConfigDeviceQueryManagerRes", res))
}

func Query(conn *websocket.Conn, manager *tables.ManagerTable, data any) {
	if !manager.Super {
		_ = conn.WriteJSON(utils.WsError("auth failed."))
		return
	}
	var param queryParam
	err := utils.AnyTrans(data, &param)
	if err != nil {
		_ = conn.WriteJSON(utils.WsError("param error"))
		return
	}
	total, devices, err := tables.DevicesQuery(param.Manager, param.Cond, param.Limit, param.Page)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsError("query devices failed"))
		return
	}
	_ = conn.WriteJSON(
		utils.WsEvent("superConfigDeviceQueryRes", utils.JsonType{"total": total, "devices": devices}),
	)
}

func Update(conn *websocket.Conn, manager *tables.ManagerTable, data any) {
	if !manager.Super {
		_ = conn.WriteJSON(utils.WsError("auth failed."))
		return
	}
	var param updateParam
	err := utils.AnyTrans(data, &param)
	if err != nil {
		_ = conn.WriteJSON(utils.WsError("param error"))
		return
	}
	device := tables.DeviceTable{Id: param.Did}
	err = device.Get()
	if err != nil {
		_ = conn.WriteJSON(utils.WsEvent("superConfigDeviceUpdateRes", utils.Fail("no such device")))
		return
	}
	device.Manager, device.Addr, device.Mark = param.Mid, param.Addr, param.Mark
	err = device.UpdateSelf()
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("superConfigDeviceUpdateRes", utils.Fail("更新失败")))
		return
	}
	_ = conn.WriteJSON(utils.WsEvent("superConfigDeviceUpdateRes", utils.Success(nil)))
}

func Assign(conn *websocket.Conn, manager *tables.ManagerTable, data any) {
	if !manager.Super {
		_ = conn.WriteJSON(utils.WsError("auth failed."))
		return
	}
	var param assignParam
	err := utils.AnyTrans(data, &param)
	if err != nil {
		_ = conn.WriteJSON(utils.WsError("param error"))
		return
	}
	err = tables.DevicesAssignManager(param.Devices, param.Manager)
	if err != nil {
		utils.Logger.Println(err)
		_ = conn.WriteJSON(utils.WsEvent("superConfigDeviceAssignRes", utils.Fail("分配失败")))
		return
	}
	_ = conn.WriteJSON(utils.WsEvent("superConfigDeviceAssignRes", utils.Success(nil)))
}
