package main

import (
	"bytes"
	"encoding/binary"
	"encoding/json"
	"testing"
)

func TestParsePingCommand(t *testing.T) {
	req, err := parseCommand([]string{"ping"})
	if err != nil {
		t.Fatalf("parseCommand returned error: %v", err)
	}
	if req.Method != "ping" {
		t.Fatalf("method = %q, want ping", req.Method)
	}
	if req.Params != nil {
		t.Fatalf("params = %#v, want nil", req.Params)
	}
}

func TestParseAddClientCommand(t *testing.T) {
	req, err := parseCommand([]string{"add-client", "--uuid", "abcdefg", "--token", "token1234"})
	if err != nil {
		t.Fatalf("parseCommand returned error: %v", err)
	}
	if req.Method != "add_client" {
		t.Fatalf("method = %q, want add_client", req.Method)
	}
	if req.Params["uuid"] != "abcdefg" || req.Params["token"] != "token1234" {
		t.Fatalf("params = %#v", req.Params)
	}
}

func TestPacket2RoundTrip(t *testing.T) {
	req := request{Method: "ping"}
	body, err := json.Marshal(req)
	if err != nil {
		t.Fatalf("json.Marshal returned error: %v", err)
	}

	var buf bytes.Buffer
	if err := writePacket(&buf, body); err != nil {
		t.Fatalf("writePacket returned error: %v", err)
	}
	if got, want := binary.BigEndian.Uint16(buf.Bytes()[:2]), uint16(len(body)); got != want {
		t.Fatalf("packet size = %d, want %d", got, want)
	}

	got, err := readPacket(&buf)
	if err != nil {
		t.Fatalf("readPacket returned error: %v", err)
	}
	if !bytes.Equal(got, body) {
		t.Fatalf("packet body = %q, want %q", got, body)
	}
}
