package parser

import (
	"log"
	"regexp"

	"github.com/golang/protobuf/proto"

	"code.justin.tv/eventbus/client/testhelpers"
	"code.justin.tv/eventbus/express/parser/eventtypes"
)

var matchUrlBase64 = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)

func GuessPayload(result *ParseResult) {
	s, ok := result.Payload.(string)
	if !ok {
		return // for now
	}

	// maybe an event bus payload
	if matchUrlBase64.MatchString(s) {
		m, err := testhelpers.DecodeSNSPayload(s)
		if err == nil {
			result.IsEventBus = true
			result.EventBus = m
			result.EventBusType = m.Header.EventType
			result.Payload = m.Payload

			// decode if it's not a no-op
			if m.Header.EventType != "" && len(m.Payload) != 0 {
				// todo check map key with m,ok form or nil check
				dest := eventtypes.MessageBuilders[m.Header.EventType]()
				// todo check err
				err = proto.Unmarshal(m.Payload, dest)
				if err != nil {
					log.Println("WARN: unable to decode EventBus message")
				}
				result.Payload = dest
			}
		}
	}

}
