package main

import (
	"bytes"
	"compress/gzip"
	"context"
	"encoding/json"
	"fmt"
	"strings"

	"code.justin.tv/creator-collab/log/errors"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handleRequest(_ context.Context, event events.KinesisEvent) error {
	for _, record := range event.Records {
		err := echoRecord(&record)
		if err != nil {
			return err
		}
	}

	return nil
}

func echoRecord(record *events.KinesisEventRecord) error {
	data := record.Kinesis.Data
	if len(data) == 0 {
		return errors.New("record.Kinesis.Data was empty")
	}

	zr, err := gzip.NewReader(bytes.NewBuffer(data))
	if err != nil {
		return err
	}
	defer zr.Close()

	var logData events.CloudwatchLogsData
	dec := json.NewDecoder(zr)
	err = dec.Decode(&logData)
	if err != nil {
		return errors.Wrap(err, "parsing record.Kinesis.Data failed", errors.Fields{
			"data": data,
		})
	}

	strBuilder := strings.Builder{}

	strBuilder.WriteString("Record:\n")
	strBuilder.WriteString(fmt.Sprintf("Log group: %s\n", logData.LogGroup))

	for _, logEvent := range logData.LogEvents {
		strBuilder.WriteString("Log event:\n")
		strBuilder.WriteString(fmt.Sprintf("Timestamp: %d\n", logEvent.Timestamp))
		strBuilder.WriteString(fmt.Sprintf("Message: %s\n", logEvent.Message))
		strBuilder.WriteString("\n")
	}

	strBuilder.WriteString("\n")

	fmt.Println(strBuilder.String())
	return nil
}

func main() {
	lambda.Start(handleRequest)
}
