package param

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

func List(conn *websocket.Conn, manager *tables.ManagerTable, data any) {
	if !manager.Super {
		_ = conn.WriteJSON(utils.WsError("auth failed."))
		return
	}
	list, err := tables.ParamsListAllForSuper()
	if err != nil {
		_ = conn.WriteJSON(utils.WsEvent("superConfigParamListRes", utils.Fail("查询参数失败")))
		return
	}
	_ = conn.WriteJSON(utils.WsEvent("superConfigParamListRes", utils.Success(list)))
}

func Update(conn *websocket.Conn, manager *tables.ManagerTable, data any) {
	if !manager.Super {
		_ = conn.WriteJSON(utils.WsError("auth failed."))
		return
	}
	var params []updateParam
	err := utils.AnyTrans(data, &params)
	if err != nil {
		_ = conn.WriteJSON(utils.WsError("param error"))
		return
	}
	for _, param := range params {
		if param.Name == "" {
			_ = conn.WriteJSON(utils.WsEvent("superConfigParamUpdateRes", utils.Fail("参数名不可为空")))
			return
		}
		pra := tables.ParamsTable{Id: param.Id}
		err = pra.Get()
		if err != nil {
			_ = conn.WriteJSON(utils.WsEvent("superConfigParamUpdateRes", utils.Fail("no such param")))
			return
		}
		pra.Describe, pra.Value = param.Name, param.Value
		err = pra.UpdateSelf()
		if err != nil {
			_ = conn.WriteJSON(utils.WsEvent("superConfigParamUpdateRes", utils.Fail("更新失败")))
			return
		}
	}
	_ = conn.WriteJSON(utils.WsEvent("superConfigParamUpdateRes", utils.Success(nil)))
	go informDevices()
}

func informDevices() {
	pra, err := tables.ParamsListAll()
	if err != nil {
		return
	}
	for _, item := range utils.SellerDevices {
		if item.Online {
			_ = item.Conn.WriteJSON(utils.WsEvent("paramsUpdate", pra))
		}
	}
}
