package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	const HOST = "localhost"
	const PORT = "8992"

	fmt.Printf("Connecting to %s:%s\n", HOST, PORT)
	conn, err := net.Dial("tcp", HOST+":"+PORT)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Couldn't connect to %s: %v\n", HOST, err)
		os.Exit(1)
	}
	defer conn.Close()

	fmt.Println("Connected")

	input := "{\"type\":\"SUBSCRIBE\"}"
	fmt.Println("Transmitting.....")
	_, err = conn.Write([]byte(input + "\n"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Couldn't write to connection: %v\n", err)
		os.Exit(1)
	}

	buf := new(strings.Builder)
	open := 0

	reader := bufio.NewReader(conn)

	for {
		char, _, err := reader.ReadRune()
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error reading from connection: %v\n", err)
			break
		}

		buf.WriteRune(char)
		if char == '{' {
			open++
		} else if char == '}' {
			open--
		}

		if open == 0 {
			processMessage(buf.String())
			buf.Reset()
		}
	}
}

func processMessage(msg string) {
	fmt.Printf("Received msg: %s\n\n", msg)
}
