package message

import (
	"io/ioutil"
	"local/truckstop/config"
	"os"
	"path"
	"testing"

	"github.com/google/uuid"
)

func TestMatrixSendDel(t *testing.T) {
	sender := testMatrix(t)
	if id, err := sender.SendTracked("hello world from unittest"); err != nil {
		t.Fatal(err)
	} else if err := sender.Remove(id); err != nil {
		t.Fatal(err)
	}
}

func TestMatrixUpdate(t *testing.T) {
	// 19:32:34: VER: matrix event: {StateKey:<nil> Sender:@bot:m.bltrucks.top Type:m.room.message Timestamp:1642471594729 ID:$n0ln9TFZrko_cBNFXeh8YyICZ3fFm17Jhz3bmZcqig4 RoomID:!OYZqtInrBCn1cyz90D:m.bltrucks.top Redacts: Unsigned:map[transaction_id:go1642471594571852423] Content:map[body:hello world from unittest format: formatted_body: msgtype:m.text] PrevContent:map[]}
	// func (m Matrix) Update(id, text string) error {
	m := testMatrix(t)
	uid := uuid.New().String()[:3]
	id, err := m.SendTracked("hello, heheheh from test matrix update " + uid)
	if err != nil {
		t.Fatal(err)
	}
	err = m.Update(id, "heheheh i updated from test matrix update "+uid)
	if err != nil {
		t.Fatal(err)
	}
	m.Receive()
}

func TestMatrixReceive(t *testing.T) {
	sender := testMatrix(t)
	if msgs, err := sender.Receive(); err != nil {
		t.Fatal(err)
	} else {
		t.Logf("%+v", msgs)
	}
}

func testMatrix(t *testing.T) Matrix {
	if len(os.Getenv("INTEGRATION")) == 0 {
		t.Skip("$INTEGRATION not set")
	}
	d := t.TempDir()
	f := path.Join(d, "config.test.json")
	b, err := ioutil.ReadFile("../config.json")
	if err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(f, b, os.ModePerm); err != nil {
		t.Fatal(err)
	}
	os.Setenv("CONFIG", f)
	if err := config.Refresh(nil); err != nil {
		t.Fatal(err)
	}
	return NewMatrix()
}
