package camera

import (
	"context"
	"errors"
	"github.com/sirupsen/logrus"
	goonvif "github.com/use-go/onvif"
	"github.com/use-go/onvif/device"
	sdkdevice "github.com/use-go/onvif/sdk/device"
	"net/http"
	"runtime/debug"
	"server/utils/logger"
	"server/utils/mqtt"
	"sync"
)

var mutex sync.Mutex

func NewDevice(camera *CameraDev) (*goonvif.Device, error) {
	defer func() {
		if err := recover(); err != nil {
			logrus.Errorf("NewDevice.Handle发生异常:%v", err)
			logrus.Errorf("NewDevice.Handle发生异常,堆栈信息:%s", string(debug.Stack()))
			go NewDevice(camera)
		}
	}()
	params := goonvif.DeviceParams{
		Xaddr:      camera.IP,
		Username:   camera.User,
		Password:   camera.Password,
		HttpClient: &http.Client{},
	}
	//初始化 ONVIF 客户端
	dev, err := goonvif.NewDevice(params)
	if err != nil {
		logrus.Errorf("摄像机%s初始化失败,原因:%s", camera.Code, err.Error())
		return nil, err
	}
	ctx := context.Background()
	getDeviceInformation := device.GetDeviceInformation{}
	getDeviceInformationResponse, err := sdkdevice.Call_GetDeviceInformation(ctx, dev, getDeviceInformation)
	if err != nil {
		logrus.Errorf("[%s]获取信息失败", camera.Code)
		return nil, err
	}
	if getDeviceInformationResponse == (device.GetDeviceInformationResponse{}) {
		logrus.Errorf("设备[%s]权限认证失败", camera.Code)
		return nil, errors.New("权限认证失败")
	}
	return dev, nil
}

func TestCameraOnline(devices map[string]*goonvif.Device) error {
	ctx := context.Background()
	var online string
	for code, dev := range devices {
		//读取设备能力信息，判断是否在线
		capabilities := device.GetCapabilities{Category: "All"}
		_, state := sdkdevice.Call_GetCapabilities(ctx, dev, capabilities)
		topic := mqtt.MqttService.GetTopic(code, mqtt.TopicDeviceCamera)
		if state != nil {
			//1表示离线
			online = "1"
		} else {
			//0表示在线
			online = "0"
		}
		mutex.Lock()
		err := mqtt.MqttService.Publish(topic, online)
		mutex.Unlock()
		if err != nil {
			logger.Logger.Errorf("Publish err = %s", err.Error())
			return err
		}
	}
	return nil
}
