package common

import (
	"encoding/json"

	"github.com/fiskerinc/cloud-services/pkg/grpc/kafka_grpc"
	"github.com/pkg/errors"
)

type TRexLog struct {
	Level      LogLevel `json:"level"`
	Timestamp  string   `json:"timestamp"`
	LineNumber int      `json:"line_number"`
	FileName   string   `json:"filename"`
	Channel    string   `json:"channel"`
	Message    string   `json:"msg"`
}
type LogTrexLog struct {
	TRexLog
	ReceivedTimestamp string `json:"received_timestamp"`
}

type TRexLogs []TRexLog

func (tl *TRexLogs) ToGrpc(data MessageRawJSON) (*kafka_grpc.TRexLogs_BatchPayload, error) {
	var logs TRexLogs
	err := json.Unmarshal(data.Data, &logs)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	var msg kafka_grpc.TRexLogs
	msg.Logs = make([]*kafka_grpc.TRexLog, len(logs))
	for i, log := range logs {
		msg.Logs[i] = &kafka_grpc.TRexLog{
			Level:      int32(log.Level),
			Timestamp:  log.Timestamp,
			LineNumber: int32(log.LineNumber),
			Filename:   log.FileName,
			Channel:    log.Channel,
			Msg:        log.Message,
		}
	}
	//msg is the type TRexLogs
	nested := kafka_grpc.TRexLogs_BatchPayload_Data{
		Data: &msg,
	}
	batchPayload := kafka_grpc.TRexLogs_BatchPayload{
		Handler:     data.Handler,
		TRexMessage: &nested,
		Version:     data.Version,
	}

	return &batchPayload, nil
}
