package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"path"

	"github.com/apex/rpc/generators/goserver"
	"github.com/apex/rpc/schema"
)

func main() {
	path := flag.String("schema", "schema.json", "Path to the schema file")
	pkg := flag.String("package", "server", "Name of the package")
	types := flag.String("types", "", "Types package to import")
	logging := flag.Bool("logging", true, "Enable logging generation")
	flag.Parse()

	s, err := schema.Load(*path)
	if err != nil {
		log.Fatalf("error: %s", err)
	}

	err = generate(os.Stdout, s, *pkg, *types, *logging)
	if err != nil {
		log.Fatalf("error: %s", err)
	}
}

// generate implementation.
func generate(w io.Writer, s *schema.Schema, pkg, types string, logging bool) error {
	out := fmt.Fprintf

	// TODO: move these to generator
	out(w, "// Do not edit, this file was generated by github.com/apex/rpc.\n\n")
	out(w, "package %s\n\n", pkg)

	out(w, "import (\n")
	out(w, "  \"context\"\n")
	out(w, "  \"net/http\"\n")
	out(w, "\n")
	out(w, "  \"github.com/apex/rpc\"\n")
	out(w, "  \"github.com/apex/log\"\n")
	if len(types) > 0 {
		out(w, "\n")
		out(w, "  \"%s\"\n", types)
	}
	out(w, ")\n\n")

	if len(types) > 0 {
		types = path.Base(types)
	}
	err := goserver.Generate(w, s, logging, types)
	if err != nil {
		return fmt.Errorf("generating client: %w", err)
	}

	return nil
}
