package parser

import (
	"crypto/sha1"
	"fmt"
	"regexp"
	"strings"

	"code.justin.tv/creator-collab/log/errors"
)

func parsePlainTextPayload(payload string) (*messageProperties, error) {
	if payload == "" {
		return nil, errors.New("message was empty")
	}

	level := ""
	if strings.Contains(payload, "panic") {
		level = "panic"
	}

	fingerprint := calcPlainTextFingerprint(payload)

	return &messageProperties{
		message:     payload,
		fingerprint: fingerprint,
		level:       level,
	}, nil
}

func calcPlainTextFingerprint(payload string) string {
	sanitized := sanitize(payload)
	return hash(sanitized)
}

func hash(s string) string {
	h := sha1.New()
	h.Write([]byte(s))
	bs := h.Sum(nil)
	return fmt.Sprintf("%x", bs)
}

func sanitize(s string) string {
	// Remove Guid
	guidRegex := regexp.MustCompile(`[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}`)
	s = guidRegex.ReplaceAllLiteralString(s, "")

	// Remove digits
	digitRegex := regexp.MustCompile(`\d`)
	return digitRegex.ReplaceAllLiteralString(s, "")

}
