package blueprint

//go:generate go-bindata -pkg blueprint -prefix data/ data/...

import (
	"bytes"
	"io/ioutil"
	"regexp"
	"text/template"

	"github.com/golang/protobuf/proto"
	"github.com/pkg/errors"

	pb "code.justin.tv/dta/rockpaperscissors/proto"
)

var (
	blueprintTemplate = template.Must(
		template.New("blueprint").Parse(string(MustAsset("enroll_blueprint.tmpl"))))
	commentsRegex = regexp.MustCompile(`(?m)^\s*#.*`)
	eolRegex      = regexp.MustCompile(`\n\s*\n`)
)

// MakeTemplate renders a ProjectMetadata protobuffer object into a nice editable blueprint.
func MakeTemplate(input *pb.ProjectMetadata) (string, error) {
	var buf bytes.Buffer
	err := blueprintTemplate.Execute(&buf, input)
	if err != nil {
		return "", errors.Wrap(err, "Error rendering blueprint template")
	}

	return buf.String(), nil
}

// ReadFile reads a file and returns a ProjectMetadata protobuffer message.
func ReadFile(filename string) (*pb.ProjectMetadata, error) {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, errors.Wrap(err, "Error reading temporary file")
	}

	return Parse(string(content))
}

// Parse string into a ProjectMetadata protobuffer message.
func Parse(content string) (*pb.ProjectMetadata, error) {
	content = commentsRegex.ReplaceAllLiteralString(content, "")
	content = eolRegex.ReplaceAllLiteralString(content, "\n")

	metadata := &pb.ProjectMetadata{}
	err := proto.UnmarshalText(content, metadata)
	if err != nil {
		return nil, errors.Wrap(err, "Error parsing blueprint")
	}

	return metadata, nil
}
