package mqtt_test

import (
	"os"
	"testing"
	"time"

	"github.com/AFASystems/presence/internal/pkg/model"
	"github.com/AFASystems/presence/internal/pkg/mqtt_client"
	"github.com/AFASystems/presence/internal/pkg/persistence"
	"github.com/boltdb/bolt"
)

func TestIncomingMQTTProcessor(t *testing.T) {
	ctx := &model.AppContext{
		Beacons: model.BeaconsList{Beacons: make(map[string]model.Beacon)},
		Settings: model.Settings{
			Last_seen_threshold: 10,
			Location_confidence: 3,
		},
	}

	tmpfile, _ := os.CreateTemp("", "testdb-*.db")
	defer os.Remove(tmpfile.Name())

	db, err := bolt.Open(tmpfile.Name(), 0600, nil)
	if err != nil {
		t.Fatal(err)
	}
	model.Db = db

	persistence.LoadState(model.Db, ctx)

	ch := mqtt_client.IncomingMQTTProcessor(20*time.Millisecond, nil, model.Db, ctx)
	msg := model.Incoming_json{MAC: "15:02:31", Hostname: "testHost", RSSI: -55}
	ch <- msg

	time.Sleep(100 * time.Millisecond)

	ctx.Beacons.Lock.RLock()
	defer ctx.Beacons.Lock.RUnlock()

	if len(ctx.LatestList.LatestList) == 0 {
		t.Fatal("latest list map to update")
	}
}
