package door

// Need net, flag for setupSockets
import (
	"flag"
	"fmt"
	"os"
	"testing"
	"time"
)

// Should tests not delete the logfiles?
const KEEP_LOGS bool = true
const VERBOSE_TEST bool = true

func TestGoto(t *testing.T) {
	GotoMap := map[string][]int{"\x1b[10;20H": {20, 10},
		"\x1b[20;10H":  {10, 20},
		"\x1b[80;120H": {120, 80},
		"\x1b[1;1H":    {1, 1},
	}

	for text, code := range GotoMap {
		gt := Goto(code[0], code[1])
		if text != gt {
			t.Errorf("Goto: Expected %#v (%#v), got %#v", text, code, gt)
		}
	}
}

func TestReadDropfileFail(t *testing.T) {
	d := Door{}

	defer func() {
		if r := recover(); r == nil {
			t.Error("ReadDropfile did not panic on missing dropfile.")
		}
	}()

	d.ReadDropfile("This_File_Will_Not_Be_Found")
}

func TestLogfileFailure(t *testing.T) {
	tmpFile, err := os.CreateTemp("", "test-*")
	if err != nil {
		panic("Cannot create temporary file")
	}

	defer func() {
		if r := recover(); r == nil {
			t.Error("Init did not panic on logfile error.")
		}
	}()

	// Remember to clean up the file afterwards
	defer os.Remove(tmpFile.Name())

	// This test should fail before we even need sockets

	var fd int = 0

	// Create door32.sys file
	dfc := DropfileConfig{2, fd, 1800, "Test BBSID", 1701, "Real Username", "Handle", 880, 28, 0, 13}

	_, err = tmpFile.WriteString(fmt.Sprintf("%d\n%d\n%d\n%s\n%d\n%s\n%s\n%d\n%d\n%d\n%d\n",
		dfc.Comm_type, dfc.Comm_handle, dfc.Baudrate, dfc.BBSID, dfc.User_number, dfc.Real_name, dfc.Handle,
		dfc.Security_level, dfc.Time_left, dfc.Emulation, dfc.Node))
	if err != nil {
		t.Error("tmpFile.WriteString:", err)
	}
	err = tmpFile.Close()
	if err != nil {
		t.Error("tmpFile.Close:", err)
	}

	d := Door{}

	// If I call d.Init() more then once flag complains about flag redefined.
	// Reset flags
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	// preset commandline args so door can init
	os.Args = []string{"door", "-d", tmpFile.Name()}
	d.Init("/badname-test")

}

func TestReadDropFile(t *testing.T) {
	tmpFile, err := os.CreateTemp("", "test-*")
	if err != nil {
		panic("Cannot create temporary file")
	}

	// Clean up the dropfile afterwards
	defer os.Remove(tmpFile.Name())

	dfc := DropfileConfig{2, 20, 1800, "Test BBSID", 1701, "Real Username", "Handle", 880, 28, 0, 12}

	_, err = tmpFile.WriteString(fmt.Sprintf("%d\n%d\n%d\n%s\n%d\n%s\n%s\n%d\n%d\n%d\n%d\n",
		dfc.Comm_type, dfc.Comm_handle, dfc.Baudrate, dfc.BBSID, dfc.User_number, dfc.Real_name, dfc.Handle,
		dfc.Security_level, dfc.Time_left, dfc.Emulation, dfc.Node))
	if err != nil {
		t.Error("tmpFile.WriteString:", err)
	}
	err = tmpFile.Close()
	if err != nil {
		t.Error("tmpFile.Close:", err)
	}

	d := Door{}
	d.ReadDropfile(tmpFile.Name())

	if dfc.Comm_type != d.Config.Comm_type {
		t.Errorf("Comm Type expected %#v, got %#v", dfc.Comm_type, d.Config.Comm_type)
	}
	if dfc.Comm_handle != d.Config.Comm_handle {
		t.Errorf("Comm Handle expected %#v, got %#v", dfc.Comm_handle, d.Config.Comm_handle)
	}
	if dfc.BBSID != d.Config.BBSID {
		t.Errorf("BBSID expected %#v, got %#v", dfc.BBSID, d.Config.BBSID)
	}
	if dfc.User_number != d.Config.User_number {
		t.Errorf("User Number expected %#v, got %#v", dfc.User_number, d.Config.User_number)
	}
	if dfc.Real_name != d.Config.Real_name {
		t.Errorf("Real Name expected %#v, got %#v", dfc.Real_name, d.Config.Real_name)
	}
	if dfc.Handle != d.Config.Handle {
		t.Errorf("Handle expected %#v, got %#v", dfc.Handle, d.Config.Handle)
	}
	if dfc.Time_left != d.Config.Time_left {
		t.Errorf("Time Left expected %#v, got %#v", dfc.Time_left, d.Config.Time_left)
	}
	if dfc.Node != d.Config.Node {
		t.Errorf("Node expected %#v, got %#v", dfc.Node, d.Config.Node)
	}
	start := time.Now()
	timeout := time.Now().Add(time.Duration(dfc.Time_left) * time.Minute)

	// Verify the start time and timeout values have been set correctly.
	startDelta := start.Sub(d.StartTime)
	timeoutDelta := timeout.Sub(d.TimeOut)

	left := d.TimeLeft()
	used := d.TimeUsed()

	if used.Seconds() > 1 {
		t.Errorf("Time Used (from door) > 1 second: %#v", used)
	}

	time_left_seconds := dfc.Time_left * 60

	if time_left_seconds-int(left.Seconds()) > 1 {
		t.Errorf("Time Left differences > 1 second: test %#v door %#v", time_left_seconds, left)
	}
	if startDelta.Seconds() > 1 {
		t.Errorf("Start Time differences: test %#v door %#v delta %#v", start, d.StartTime, startDelta)
	}
	if timeoutDelta.Seconds() > 1 {
		t.Errorf("TimeOut differences: test %#v door %#v delta %#v", timeout, d.TimeOut, timeoutDelta)
	}
}

func TestDetectFail(t *testing.T) {
	tmpFile, err := os.CreateTemp("", "test-*")
	if err != nil {
		panic("Cannot create temporary file")
	}

	// Remember to clean up the file afterwards

	defer os.Remove(tmpFile.Name())

	// establish network socket connection to set Comm_handle
	server, client := setupSockets()

	// We're not testing closed connections, so:
	defer server.Close()
	defer client.Close()

	// Send nothing
	var fd int = socket_to_fd(client)
	defer close_fd(fd)

	// Create door32.sys file
	dfc := DropfileConfig{2, fd, 1800, "Test BBSID", 1701, "Real Username", "Handle", 880, 28, 0, 13}

	_, err = tmpFile.WriteString(fmt.Sprintf("%d\n%d\n%d\n%s\n%d\n%s\n%s\n%d\n%d\n%d\n%d\n",
		dfc.Comm_type, dfc.Comm_handle, dfc.Baudrate, dfc.BBSID, dfc.User_number, dfc.Real_name, dfc.Handle,
		dfc.Security_level, dfc.Time_left, dfc.Emulation, dfc.Node))
	if err != nil {
		t.Error("tmpFile.WriteString:", err)
	}
	err = tmpFile.Close()
	if err != nil {
		t.Error("tmpFile.Close:", err)
	}

	d := Door{ReaderCanClose: true}

	// Because we're not the only one calling door.Init(), the
	// door global variables might be from a previous test run.

	Unicode = false
	CP437 = false
	Full_CP437 = false
	Width = 0
	Height = 0

	// If I call d.Init() more then once flag complains about flag redefined.
	// Reset flags
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	// preset commandline args so door can init
	os.Args = []string{"door", "-d", tmpFile.Name()}
	d.Init("menu-test")

	t.Logf("Init completed.")
	defer d.Close()
	// clean up log file
	// I don't need to.  Tests are run in /tmp/go-buildNNNN.
	// defer os.Remove("menu-test-13.log")

	if Unicode || CP437 {
		t.Errorf("Expected FALSE, got Unicode %t CP437 %t", Unicode, CP437)
	}

	if Width != 0 || Height != 0 {
		t.Errorf("Expected 0, 0, got Width %d, Height %d", Width, Height)
	}

	t.Logf("Closing server and client...")
	server.Close()
	client.Close()

	// time.Sleep(time.Duration(1) * time.Second)
	t.Logf("Done.")
}