package instrumentor

import (
	"io"
	"os"
	"path"
	"text/template"

	"github.com/antithesishq/antithesis-sdk-go/tools/antithesis-go-instrumentor/common"
)

func GenerateNotifierSource(notifierDir string, notifierInfo *NotifierInfo) {
	var tmpl *template.Template
	var err error

	tmpl = template.New("notifier")

	if tmpl, err = tmpl.Parse(getNotifierText()); err != nil {
		panic(err)
	}

	var outFile io.Writer
	if outFile, err = notifierOutputFile(notifierDir, notifierInfo.logWriter); err != nil {
		panic(err)
	}

	if err = tmpl.Execute(outFile, notifierInfo); err != nil {
		panic(err)
	}
}

func getNotifierText() string {
	const text = `package {{.NotifierPackage}}

// ----------------------------------------------------
// Generated by Antithesis instrumentor - do not modify
// ----------------------------------------------------

import "{{.InstrumentationPackageName}}"

func init() {
	instrumentation.InitializeModule("{{.SymbolTableName}}", {{.EdgeCount}})
}

func Notify(edge int) {
	instrumentation.Notify(edge)
}

`

	return text
}

func notifierOutputFile(dir_name string, logWriter *common.LogWriter) (*os.File, error) {
	output_file_name := path.Join(dir_name, common.GENERATED_NOTIFIER_SOURCE)

	var file *os.File
	var err error
	if file, err = os.OpenFile(output_file_name, os.O_RDWR|os.O_CREATE, 0644); err != nil {
		file = nil
	}
	if file != nil {
		if err = file.Truncate(0); err != nil {
			file = nil
		}
	}
	if err == nil {
		logWriter.Printf("Notifier file: %q\n", output_file_name)
	} else {
		logWriter.Printf("Unable to generate Notifier file: %q\n", output_file_name)
	}
	return file, err
}
