package jsontable

import (
	"testing"

	"bytes"
	"encoding/json"

	"github.com/olekukonko/tablewriter"
)

var TestLine = []string{"1", "2"}
var TestGroup = [][]string{{"1", "2", "3"}, {"a", "teohunteohu", "c", "d"}, {"☺", "☹"}}
var TestKeys = []string{"key0", "key1", "key2"}

// test creation
func TestNewTable(t *testing.T) {
	var b bytes.Buffer
	tbl := NewJSONTable(&b)
	if tbl.NumLines() != 0 {
		t.Fatalf("Something went weird when making table (should have 0 lines)")
	}
}

// test adding things
func TestTableAdd(t *testing.T) {
	var b bytes.Buffer
	tbl := NewJSONTable(&b)

	tbl.Append(TestLine)
	if tbl.NumLines() != 1 {
		t.Fatalf("Appending a line does not result in a length of 1.")
	}

	tbl.AppendBulk(TestGroup)
	numlines := tbl.NumLines()
	if numlines != (len(TestGroup) + 1) {
		t.Fatalf("Appending two lines does not result in a length of 4 (length is %d).", numlines)
	}
}

// test JSON output is parsable
func TestJsonParsable(t *testing.T) {
	var b bytes.Buffer
	tbl := NewJSONTable(&b)

	tbl.AppendBulk(TestGroup)
	tbl.SetHeader(TestKeys)

	tbl.JSONRender()

	var son []map[string]interface{}

	err := json.Unmarshal(b.Bytes(), &son)

	if err != nil {
		t.Fatalf("Did not produce parsable JSON: %s", err.Error())
	}
}

// test identical commands to a tablewriter and jsontable produce the same rendered output
func TestTableWriter(t *testing.T) {
	var bjson bytes.Buffer
	var btable bytes.Buffer

	tbl := NewJSONTable(&bjson)

	tbl.AppendBulk(TestGroup)
	tbl.SetHeader(TestKeys)
	tbl.Render()

	wtbl := tablewriter.NewWriter(&btable)

	wtbl.AppendBulk(TestGroup)
	wtbl.SetHeader(TestKeys)
	wtbl.Render()

	if bytes.Compare(bjson.Bytes(), btable.Bytes()) != 0 {
		t.Fatalf("JSON table and TableWriter produce non-identical outputs.\n%s\n%s", bjson.Bytes(), btable.Bytes())
	}
}

/// FIXME test different output formats when captions etc. are added