package doc

import (
	"bufio"
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"

	"github.com/spf13/cobra"
)

func TestGenAsciidocDoc(t *testing.T) {
	// We generate on subcommand so we have both subcommands and parents.
	buf := new(bytes.Buffer)
	if err := GenAsciidoc(echoCmd, buf); err != nil {
		t.Fatal(err)
	}
	output := buf.String()

	checkStringContains(t, output, echoCmd.Long)
	checkStringContains(t, output, echoCmd.Example)
	checkStringContains(t, output, "boolone")
	checkStringContains(t, output, "rootflag")
	checkStringContains(t, output, rootCmd.Short)
	checkStringContains(t, output, echoSubCmd.Short)
	checkStringOmits(t, output, deprecatedCmd.Short)
	checkStringContains(t, output, "Options inherited from parent commands")
	// check the output.
	//println(output)
}

func TestGenAsciidocDocWithNoLongOrSynopsis(t *testing.T) {
	// We generate on subcommand so we have both subcommands and parents.
	buf := new(bytes.Buffer)
	if err := GenAsciidoc(dummyCmd, buf); err != nil {
		t.Fatal(err)
	}
	output := buf.String()

	checkStringContains(t, output, dummyCmd.Example)
	checkStringContains(t, output, dummyCmd.Short)
	checkStringContains(t, output, "Options inherited from parent commands")
	checkStringOmits(t, output, "=== Synopsis")
	// check the output.
	//println(output)
}

func TestGenAsciidocNoHiddenParents(t *testing.T) {
	// We generate on subcommand so we have both subcommands and parents.
	for _, name := range []string{"rootflag", "strtwo"} {
		f := rootCmd.PersistentFlags().Lookup(name)
		f.Hidden = true
		defer func() { f.Hidden = false }()
	}
	buf := new(bytes.Buffer)
	if err := GenAsciidoc(echoCmd, buf); err != nil {
		t.Fatal(err)
	}
	output := buf.String()

	checkStringContains(t, output, echoCmd.Long)
	checkStringContains(t, output, echoCmd.Example)
	checkStringContains(t, output, "boolone")
	checkStringOmits(t, output, "rootflag")
	checkStringContains(t, output, rootCmd.Short)
	checkStringContains(t, output, echoSubCmd.Short)
	checkStringOmits(t, output, deprecatedCmd.Short)
	checkStringOmits(t, output, "Options inherited from parent commands")
	// check the output.
	//println(output)
}

func TestGenAsciidocNoGenTag(t *testing.T) {
	echoCmd.DisableAutoGenTag = true
	defer func() { echoCmd.DisableAutoGenTag = false }()

	// We generate on a subcommand so we have both subcommands and parents
	buf := new(bytes.Buffer)
	if err := GenAsciidoc(echoCmd, buf); err != nil {
		t.Fatal(err)
	}
	output := buf.String()

	unexpected := translate("#HISTORY")
	checkStringOmits(t, output, unexpected)
	unexpected = translate("Auto generated by spf13/cobra")
	checkStringOmits(t, output, unexpected)
	// check the output.
	//println(output)
}

func TestGenAsciidocNoTag(t *testing.T) {
	rootCmd.DisableAutoGenTag = true
	defer func() { rootCmd.DisableAutoGenTag = false }()

	buf := new(bytes.Buffer)
	if err := GenAsciidoc(rootCmd, buf); err != nil {
		t.Fatal(err)
	}
	output := buf.String()

	checkStringOmits(t, output, "Auto generated")
}

func TestGenAsciiDocSeeAlso(t *testing.T) {
	rootCmd := &cobra.Command{Use: "root", Run: emptyRun}
	aCmd := &cobra.Command{Use: "aaa", Run: emptyRun, Hidden: true} // #229
	bCmd := &cobra.Command{Use: "bbb", Run: emptyRun}
	cCmd := &cobra.Command{Use: "ccc", Run: emptyRun}
	rootCmd.AddCommand(aCmd, bCmd, cCmd)

	buf := new(bytes.Buffer)
	if err := GenAsciidoc(rootCmd, buf); err != nil {
		t.Fatal(err)
	}
	scanner := bufio.NewScanner(buf)

	if err := assertLineFound(scanner, "== SEE ALSO"); err != nil {
		t.Fatalf("Couldn't find SEE ALSO section header: %v", err)
	}
	if err := assertNextLineEquals(scanner, ""); err != nil {
		t.Fatalf("First line after SEE ALSO wasn't empty line: %v", err)
	}
	if err := assertNextLineEquals(scanner, "* xref:root_bbb.adoc[root bbb]	 - "); err != nil {
		t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err)
	}
}

func TestGenAsciidocTree(t *testing.T) {
	c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}

	tmpdir, err := ioutil.TempDir("", "test-gen-asciidoc-tree")
	if err != nil {
		t.Fatalf("Failed to create tmpdir: %v", err)
	}
	defer os.RemoveAll(tmpdir)

	if err := GenAsciidocTree(c, tmpdir); err != nil {
		t.Fatalf("GenAsciidocTree failed: %v", err)
	}

	if _, err := os.Stat(filepath.Join(tmpdir, "do.adoc")); err != nil {
		t.Fatalf("Expected file 'do.adoc' to exist")
	}
}

func TestGenAsciidocTreeViaEchoCmd(t *testing.T) {

	tmpdir, err := ioutil.TempDir("", "test-gen-asciidoc-tree-echocmd")
	if err != nil {
		t.Fatalf("Failed to create tmpdir: %v", err)
	}
	// Note: comment this out for a dirty hack to get the generated files to hang around after the test.
	defer os.RemoveAll(tmpdir)

	if err := GenAsciidocTree(echoCmd, tmpdir); err != nil {
		t.Fatalf("TestGenAsciidocTreeViaEchoCmd failed: %v", err)
	}
	// Check the three files are generated.
	// check for root
	if _, err := os.Stat(filepath.Join(tmpdir, "root_echo.adoc")); err != nil {
		t.Fatalf("Expected file 'root_echo.adoc' to exist")
	}
	// Check sub command
	if _, err := os.Stat(filepath.Join(tmpdir, "root_echo_echosub.adoc")); err != nil {
		t.Fatalf("Expected file 'root_echo_echosub.adoc' to exist")
	}
	// check sub command.
	if _, err := os.Stat(filepath.Join(tmpdir, "root_echo_times.adoc")); err != nil {
		t.Fatalf("Expected file 'root_echo_times.adoc' to exist")
	}
}

func BenchmarkGenAsciidocToFile(b *testing.B) {
	file, err := ioutil.TempFile("", "")
	if err != nil {
		b.Fatal(err)
	}
	defer os.Remove(file.Name())
	defer file.Close()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if err := GenAsciidoc(rootCmd, file); err != nil {
			b.Fatal(err)
		}
	}
}

func TestAsciidocPrintFlagsHidesShortDeperecated(t *testing.T) {
	c := &cobra.Command{}
	c.Flags().StringP("foo", "f", "default", "Foo flag")
	assertNoErr(t, c.Flags().MarkShorthandDeprecated("foo", "don't use it no more"))

	buf := new(bytes.Buffer)
	manPrintFlags(buf, c.Flags())

	got := buf.String()
	expected := "**--foo**=\"default\"\n\tFoo flag\n\n"
	if got != expected {
		t.Errorf("Expected %v, got %v", expected, got)
	}
}