package camera

import (
	goonvif "github.com/use-go/onvif"
	"gopkg.in/yaml.v2"
	"os"
	"server/edge/util/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 {
	var conf DeviceConfig
	filePath := "./edge/dev/dev.yaml"
	if f, err := os.Open(filePath); err != nil {
		panic(err)
	} else {
		err := yaml.NewDecoder(f).Decode(&conf)
		if err != nil {
			panic(err)
		}
	}
	CameraDevices = make(map[string]*goonvif.Device)
	for _, v := range conf.CameraDevs {
		newDevice, err := NewDevice(v)
		if err != nil {
			return err
		}
		if newDevice != nil {
			CameraDevices[v.Code] = newDevice
		}
	}
	return nil
}
