package caddyhugo

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"os/exec"
	"sync"
	"testing"

	"git.stephensearles.com/stephen/acedoc"
)

type World struct {
	CH         *CaddyHugo
	BlogFolder string
}

func (w *World) Clean() {
	if w.BlogFolder != "" {
		os.RemoveAll(w.BlogFolder)
	}
}

func NewWorld(t *testing.T) *World {
	dir, err := ioutil.TempDir("", "caddy-hugo2-test-")
	if err != nil {
		t.Fatalf("error initializing test environment: %v", err)
	}

	w := &World{BlogFolder: dir}

	cmd := exec.Command("hugo", "new", "site", dir)
	cmd.Dir = dir
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("error initializing test site: %v\n\n%v", err, string(out))
	}

	w.CH = &CaddyHugo{}
	w.CH.Setup(dir)

	return w
}

type WebsocketTester struct {
	receivedPointer int
	received        [][]byte
	wroteMessages   []Message
	wroteDeltas     []acedoc.Delta
	mtx             sync.Mutex
}

// ReadJSON reads the next pending message from the "client" into v
func (ws *WebsocketTester) ReadJSON(v interface{}) error {
	ws.mtx.Lock()
	defer ws.mtx.Unlock()

	if len(ws.received) <= ws.receivedPointer {
		return nil
	}

	err := json.Unmarshal(ws.received[ws.receivedPointer], v)
	ws.receivedPointer++
	return err
}

// WriteJSON "sends" a message, v, to the "client"
func (ws *WebsocketTester) WriteJSON(v interface{}) error {
	ws.mtx.Lock()
	defer ws.mtx.Unlock()

	m, ok := v.(Message)
	if !ok {
		panic("wrong type written to WebsocketTester")
	}

	ws.wroteMessages = append(ws.wroteMessages, m)
	ws.wroteDeltas = append(ws.wroteDeltas, m.Deltas...)

	return nil
}

// ReceiveJSON queues a message to be sent to the client
func (ws *WebsocketTester) ReceiveJSON(v interface{}) error {
	ws.mtx.Lock()
	defer ws.mtx.Unlock()

	out, err := json.Marshal(v)
	if err != nil {
		return err
	}

	ws.received = append(ws.received, out)
	return nil
}
