package ports_test

import (
	"net"
	"testing"
	"time"

	"context"

	"git.t-juice.club/torjus/apiary/honeypot/ports"
)

func TestServer(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	store := &ports.MemoryStore{}
	server := ports.New(store)
	server.IP = "127.0.0.1"

	server.AddTCPPort("2555")

	go server.Start(ctx)
	time.Sleep(1 * time.Second)

	rAddr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(server.IP, "2555"))
	if err != nil {
		t.Fatalf("Error resolving remote address: %s", err)
	}
	conn, err := net.DialTCP("tcp", nil, rAddr)
	if err != nil {
		t.Fatalf("Dialing server returned error: %s", err)
	}
	conn.Write([]byte("LOL"))
	conn.Close()
	time.Sleep(1 * time.Second)
	cancel()

	attempts, err := store.List()
	if err != nil {
		t.Fatalf("Getting attempts from store returned error: %s", err)
	}
	if len(attempts) != 1 {
		t.Fatalf("Wrong amount of attempts in store: %d", len(attempts))
	}
}
