// Command burntsushi-tester satisfies BurntSushi's toml-test interface for testing
// TOML decoders. Namely, it accepts TOML on stdin and outputs JSON on stdout.
// See: https://github.com/BurntSushi/toml-test
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"
	"time"

	"git.makaay.nl/mauricem/go-toml/parse"
	"github.com/pkg/profile"
)

var doProfile *int

func init() {
	doProfile = flag.Int("p", 0, "Perform pprof profiling (value is number of run loops)")
	flag.Usage = usage
	flag.Parse()
}

func usage() {
	log.Printf("Usage: %s < <path to TOML-file>\n", path.Base(os.Args[0]))
	flag.PrintDefaults()

	os.Exit(1)
}

func main() {
	if *doProfile > 0 {
		fmt.Println("Profiling ...")
		inputBytes, _ := ioutil.ReadAll(os.Stdin)
		inputStr := string(inputBytes)
		p := profile.Start()
		start := time.Now()
		for i := 0; i < *doProfile; i++ {
			parse.Run(inputStr)
			fmt.Printf("cycle %d / %d\r", i+1, *doProfile)
		}
		duration := time.Since(start)
		p.Stop()
		fmt.Printf("\n")
		fmt.Println("Duration:", duration)
		return
	}

	toml, err := parse.Run(os.Stdin)
	if err != nil {
		log.Fatalf("Error decoding TOML: %s", err)
	} else {
		fmt.Println(toml.MakeSushi())
	}
}
