package node

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"testing"
	"time"

	"git.autistici.org/ale/autoradio"
)

var testParams = &liquidsoapParams{
	SourceURL:      "http://localhost/stream.ogg",
	TargetIP:       "localhost",
	TargetPort:     80,
	TargetMount:    "/stream.mp3",
	TargetUsername: "sourceuser",
	TargetPassword: "password",
	Format:         "mp3",
	BitRate:        64,
	SampleRate:     22050,
	Channels:       2,
}

func TestLiquidsoapParams_New(t *testing.T) {
	mount := &autoradio.Mount{
		Name:     "/stream.mp3",
		Username: "sourceuser",
		Password: "password",
		Transcoding: &autoradio.EncodingParams{
			SourceName: "/stream.ogg",
			Format:     "mp3",
			BitRate:    64,
			SampleRate: 22050,
			Channels:   2,
		},
	}

	params := newLiquidsoapParams(mount)
	expected := testParams
	if !params.Equal(expected) {
		t.Fatalf("newLiquidsoapParams(): got %v, want %v", params, expected)
	}
}

func TestLiquidsoapParams_Render(t *testing.T) {
	var b bytes.Buffer
	params := testParams
	if err := params.Render(&b); err != nil {
		t.Fatal(err)
	}
	if b.Len() == 0 {
		t.Fatal("empty output")
	}
}

func TestLiquidsoapController(t *testing.T) {
	// Create a fake 'liquidsoap' binary that accepts all
	// parameters and waits forever.
	tmpf, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}
	io.WriteString(tmpf, "#!/bin/sh\nsleep 3600\n")
	tmpf.Close()
	os.Chmod(tmpf.Name(), 0755)
	defer os.Remove(tmpf.Name())
	*liquidsoapBin = tmpf.Name()

	l, err := newLiquidsoap(testParams)
	if err != nil {
		t.Fatal(err)
	}
	l.restartDelay = 0

	l.Start()
	time.Sleep(50 * time.Millisecond)
	if l.process == nil {
		t.Fatal("program not started")
	}

	l.Stop()
	if l.process != nil {
		t.Fatal("program not cleaned up properly")
	}
}