package camera

import (
	"github.com/sirupsen/logrus"
	goonvif "github.com/use-go/onvif"
	"server/utils/mqtt"
	"sync"
)

var CameraDevices map[string]*goonvif.Device
var _once sync.Once
var _single *CameraDeviceMgr

type CameraDeviceMgr struct {
	downQueue      mqtt.MlQueue
	mapTopicHandle map[string]func(m mqtt.Message)
	mapDevice      map[string]*CameraDev
}

// CameraDeviceMgr 单例
func GetCameraDeviceMgr() *CameraDeviceMgr {
	_once.Do(func() {
		_single = &CameraDeviceMgr{
			downQueue:      *mqtt.NewQueue(100),
			mapTopicHandle: make(map[string]func(m mqtt.Message)),
			mapDevice:      make(map[string]*CameraDev),
		}
	})
	return _single
}

// 初始化
func (c CameraDeviceMgr) InitAllCameraDevice() error {
	if err := LoadCameraDevConfig(); err != nil {
		logrus.Errorf("加载配置文件失败:%s", err.Error())
		return err
	}

	CameraDevices = make(map[string]*goonvif.Device)
	for _, v := range cameraDevConfig.Rtu {
		c.mapDevice[v.IP] = &CameraDev{
			Code:       v.Code,
			IP:         v.IP,
			Name:       v.Name,
			Brand:      v.Brand,
			Model:      v.Model,
			DevType:    v.DevType,
			User:       v.User,
			Password:   v.Password,
			RtmpServer: v.RtmpServer,
			WebServer:  v.WebServer,
			Event:      v.Event,
			Gb28181:    v.Gb28181,
		}
		newDevice, err := NewDevice(c.mapDevice[v.IP])
		if err != nil {
			return err
		}
		if newDevice != nil {
			CameraDevices[v.Code] = newDevice
		}
	}
	return nil
}
