package etcdutil

import (
	"reflect"
	"testing"

	"github.com/coreos/etcd/integration"
	. "github.com/pingcap/check"
	"github.com/pingcap/wormhole/pkg/whpb"
	"golang.org/x/net/context"
)

var (
	etcdMockCluster *integration.ClusterV3
	etcdCli         *Client
	ctx             context.Context
)

var _ = Suite(&testEtcdutilSuite{})

type testEtcdutilSuite struct{}

func TestSaveAndLoadSchemaDetail(t *testing.T) {
	cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer cluster.Terminate(t)
	etcd := NewClient(cluster.RandClient(), "wormhole")

	err := etcd.SaveSchemaDetail("127.0.0.1", 3306, "foo", "bar", &whpb.SchemaDetail{Detail: []byte("abc")})
	if err != nil {
		t.Fatalf("save schema detail error %s", err.Error())
	}

	result := &whpb.SchemaDetail{}
	exists, err := etcd.LoadSchemaDetail("127.0.0.1", 3306, "foo", "bar", result)
	if err != nil {
		t.Fatal(err)
	}
	if !exists {
		t.Fatal("schema info not exists")
	}

	if string(result.Detail) != "abc" {
		t.Fatal("detail not matched")
	}
}

func TestSaveAndLoadSchemaDetails(t *testing.T) {
	cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer cluster.Terminate(t)
	etcd := NewClient(cluster.RandClient(), "wormhole")

	content := "abc"

	host := "127.0.0.1"
	port := int32(3306)

	cases := []struct {
		schema string
		table  string
	}{
		{"foo", "bar"},
		{"foo1", ""},
		{"a/b", "c/d"},
	}

	expectedDetails := make(map[string]map[string]*whpb.SchemaDetail)
	for _, c := range cases {
		err := etcd.SaveSchemaDetail(host, port, c.schema, c.table, &whpb.SchemaDetail{Schema: c.schema, Table: c.table, Detail: []byte(content)})
		if err != nil {
			t.Fatalf("save schema detail error %s", err.Error())
		}
		if _, ok := expectedDetails[c.schema]; !ok {
			expectedDetails[c.schema] = make(map[string]*whpb.SchemaDetail)
		}
		if c.table == "" {
			continue
		}
		expectedDetails[c.schema][c.table] = &whpb.SchemaDetail{Schema: c.schema, Table: c.table, Detail: []byte(content)}
	}

	details := make(map[string]map[string]*whpb.SchemaDetail)
	err := etcd.LoadSchemaDetails(host, port, details)
	if err != nil {
		t.Fatalf("load schemas details error %s", err.Error())
	}

	if !reflect.DeepEqual(details, expectedDetails) {
		t.Fatalf("details not matched. got %+v, expected %+v", details, expectedDetails)
	}
}
