package common

import (
	"context"
	"fmt"
	"game-driver/pkg/utils"
	"github.com/eclipse/paho.golang/paho"
	"go.uber.org/zap"
	"sync"
	"sync/atomic"
)

type DeviceMan interface {
	sync.Locker
	Status() int
	PublishStatus()
}

type Device struct {
	mu sync.Mutex
	C  context.Context

	topic    string
	status   atomic.Int32
	OnChange func()
}

func (d *Device) Lock() {
	defer d.OnChange()
	d.mu.Lock()
	d.status.Store(1)
	zap.S().Infoln("设备上锁")
}

func (d *Device) Unlock() {
	defer d.OnChange()
	d.status.Store(0)
	d.mu.Unlock()
	zap.S().Infoln("设备解锁")
}

func (d *Device) Status() int {
	return int(d.status.Load())
}

// PublishStatus 推送设备状态
func (d *Device) PublishStatus() {
	err := utils.GlobalMqttClient.AwaitConnection(d.C)
	if err != nil {
		return
	}
	_, _ = utils.GlobalMqttClient.Publish(d.C, &paho.Publish{
		Topic:   d.topic,
		Payload: []byte(fmt.Sprint(d.Status())),
		QoS:     1,
	})
}

func DefaultDevice(ctx context.Context, topic string) *Device {
	return &Device{
		C:     ctx,
		topic: topic,
	}
}

func NewDevice(ctx context.Context, topic string, onChange func()) *Device {
	return &Device{
		C:        ctx,
		topic:    topic,
		OnChange: onChange,
	}
}
