package zkeeper

import (
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/samuel/go-zookeeper/zk"
)

var (
	zkc *ZkClient
)

func setup() {
	var err error
	zkc, err = NewZkClient([]string{"192.168.0.198:2181"}, "/kg", "kingame", "wz5A2oCcGSR60O07", 5, on_node_event)
	if err != nil {
		fmt.Println("error")
	}
	fmt.Println(zkc.timeout)
}

func teardown() {
	zkc.Close()
}

func on_node_event(c *ZkClient, path string, ev zk.EventType) {
	fmt.Println("path:", path, "event", ev)
}

func TestCreateEmpNode(t *testing.T) {
	fmt.Println(zkc.timeout)
	err := zkc.CreateEmpNode("/kg/test", []byte("testing"))
	if err != nil {
		t.Errorf("error %v\n", err)
	}
}

func TestGetNodeData(t *testing.T) {
	bytes, err := zkc.GetNodeData("/kg/conf/servers/redis")
	if err != nil {
		t.Errorf("error %v\n", err)
		return
	}
	fmt.Println(string(bytes))
}

func TestGetChildren(t *testing.T) {
	chs, err := zkc.GetChildren("app")
	if err != nil {
		t.Errorf("error:%v\n", err)
		return
	}
	t.Log("children", chs)
}

func TestSetNodeData(t *testing.T) {
	err := zkc.SetNodeData("/kg/app/agents", []byte("hello"))
	if nil != err {
		t.Error(err)
	}
}

func TestWatchNode(t *testing.T) {
	err := zkc.WatchNode("test")
	if err != nil {
		return
	}
	time.Sleep(time.Duration(60) * time.Second)
}

func TestWatchChildren(t *testing.T) {
	err := zkc.WatchChildren("/kg")
	if err != nil {
		t.Errorf("error:%v\n", err)
	}
	time.Sleep(time.Duration(60) * time.Second)
}

func TestMain(m *testing.M) {
	setup()
	code := m.Run()
	teardown()
	fmt.Println("init")
	os.Exit(code)
}
