package zooKeeperMgr

import (
	"fmt"
	"strings"

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

// 级联创建path节点（如果中间节点不存在，则创建）
func CascadeCreate(conn *zk.Conn, path string) error {
	if path == "" {
		return nil
	}

	subPathArr := strings.Split(path, "/")
	path = ""
	var data = []byte("")
	var flags int32 = 0
	var acls = zk.WorldACL(zk.PermAll)

	for i := 0; i < len(subPathArr); i++ {
		// Omit the first one which is /
		if subPathArr[i] == "" {
			continue			
		}

		path += fmt.Sprintf("/%s",subPathArr[i])
		fmt.Printf("Path:%s\n",path)
		exists, _, err := conn.Exists(path)
		if err != nil {
			return err
		}
		if exists {
			continue
		}

		retPath, err := conn.Create(path, data, flags, acls)
		if err != nil {
			if err == zk.ErrNodeExists {
				fmt.Println(err)
				continue
			}
			return err
		}
		fmt.Printf("ZooKeeper created:%s\n", retPath)
	}

	return nil
}
