package devices

import (
	"errors"
	"gorm.io/gorm"
	"server/dao/devices"
	"server/model/common/request"
	model "server/model/devices"
	"server/utils/logger"
)

type GateWayService struct{}

func (gateWayService *GateWayService) GetGateWayInfoList(info request.PageInfo) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	keyword := info.Keyword

	gatewayList, total, err := devices.QueryGateWayInfoList(limit, offset, keyword)

	var details []model.GatewayDetails

	for _, gateWay := range gatewayList {
		detail := model.GatewayDetails{Gateway: gateWay}
		screensList, _ := devices.QueryScreensToDetail(gateWay.ID)
		cameraList, _ := devices.QueryCameraToDetail(gateWay.ID)
		radarList, _ := devices.QueryRadarToDetail(gateWay.ID)

		detail.RelationDev.Screens = screensList
		detail.RelationDev.Camera = cameraList
		detail.RelationDev.Radar = radarList

		details = append(details, detail)
	}

	return details, total, err
}

func (gateWayService *GateWayService) AddGateway(way devices.GateWay) error {
	err := way.IsExistedByCode()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		logger.Logger.Errorf("Create IsExistedByCode \n")
		return errors.New("设备编码已存在！")
	}

	err = way.AddGateway()
	return err
}

func (gateWayService *GateWayService) UpdateGateway(way devices.GateWay) error {
	err := way.UpdateGateway()
	return err
}

func (gateWayService *GateWayService) DelGateway(id int) error {
	way := devices.GateWay{}
	err := way.DelGateway(id)
	return err
}

func (gateWayService *GateWayService) PublicGateway() (interface{}, error) {
	way := devices.GateWay{}
	list, err := way.PublicGateway()
	return list, err
}
