package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/elastic/go-libaudit/v2"
	"github.com/elastic/go-libaudit/v2/aucoalesce"
	"github.com/elastic/go-libaudit/v2/auparse"
)

type EventHandler struct{}

func (h *EventHandler) ReassemblyComplete(msgs []*auparse.AuditMessage) {
	event, err := aucoalesce.CoalesceMessages(msgs)
	if err != nil {
		fmt.Printf("coalesce messages error: %v", err)
	}
	fmt.Println("---------------------------")
	j, _ := json.MarshalIndent(event, "", " ")
	fmt.Printf("%s\n", string(j))
	fmt.Println("---------------------------")
}

func (h *EventHandler) EventsLost(count int) {
	fmt.Fprintf(os.Stderr, "=== event lost: %d \n", count)
}

func main() {
	cli, err := libaudit.NewMulticastAuditClient(nil)
	if err != nil {
		log.Fatalf("failed to create audit client: %v", err)
	}
	defer cli.Close()

	handler := &EventHandler{}
	rea, err := libaudit.NewReassembler(256, time.Second*2, handler)
	if err != nil {
		log.Printf("%v", err)
		return
	}
	defer rea.Close()

	go func() {
		ticker := time.NewTicker(time.Second)
		defer ticker.Stop()
		for range ticker.C {
			if rea.Maintain() != nil {
				break
			}
		}
	}()

	for {
		rawMsg, err := cli.Receive(false)
		if err != nil {
			break
		}
		_ = rea.Push(rawMsg.Type, rawMsg.Data)
	}
}
