package eventstreams

import (
	"strconv"
	"time"

	"code.justin.tv/eventbus/controlplane/internal/db"
	"code.justin.tv/eventbus/controlplane/rpc"
	"github.com/golang/protobuf/ptypes"
)

func eventStreamToRPC(model *db.EventStream, authorizedFields []*db.AuthorizedField) *rpc.EventStream {
	//ts, _ := ptypes.TimestampProto(model.ActiveSince) TODO: add to DB model and do migration
	ts, _ := ptypes.TimestampProto(time.Now())
	eventStream := &rpc.EventStream{
		EventType:        model.EventType.Name,
		Environment:      model.Environment,
		DisplayName:      model.EventType.Name,        // deprecated
		ShortDescription: model.EventType.Description, //deprecated
		Description:      model.EventType.Description,
		ActiveSince:      ts, // TODO: fix
		Schema:           model.Schema,
		RepoFilepath:     model.EventType.RepoFilePath,
		Deprecated:       model.EventType.Deprecated,
		LdapGroup:        model.EventType.LDAPGroup,
	}
	for _, authField := range authorizedFields {
		eventStream.AuthorizedFields = append(eventStream.AuthorizedFields, &rpc.AuthorizedField{
			MessageName: authField.MessageName,
			FieldName:   authField.FieldName,
		})
	}
	return eventStream
}

func eventTypesToRPC(ets []*db.EventType) []*rpc.EventType {
	out := make([]*rpc.EventType, 0)
	for _, et := range ets {
		out = append(out, eventTypeToRPC(et))
	}
	return out
}

func eventTypeToRPC(model *db.EventType) *rpc.EventType {
	return &rpc.EventType{
		Id:           strconv.Itoa(model.ID),
		Name:         model.Name,
		Description:  model.Description,
		RepoFilepath: model.RepoFilePath,
		Deprecated:   model.Deprecated,
		LdapGroup:    model.LDAPGroup,
	}
}
