/*
 * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.yangtools.yang.data.api.schema;

import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import java.util.Iterator;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;

/**
 * A set of utility methods for interacting with {@link NormalizedNode} objects.
 */
@Beta
public final class NormalizedNodes {
    private static final int STRINGTREE_INDENT = 4;

    private NormalizedNodes() {
        throw new UnsupportedOperationException("Utility class should not be instantiated");
    }

    public static Optional<NormalizedNode<?, ?>> findNode(final YangInstanceIdentifier rootPath, final NormalizedNode<?, ?> rootNode, final YangInstanceIdentifier childPath) {
        final Optional<YangInstanceIdentifier> relativePath = childPath.relativeTo(rootPath);
        if (relativePath.isPresent()) {
            return findNode(rootNode, relativePath.get());
        } else {
            return Optional.absent();
        }
    }

    public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree, final YangInstanceIdentifier path) {
        checkNotNull(tree, "Tree must not be null");
        checkNotNull(path, "Path must not be null");

        Optional<NormalizedNode<?, ?>> currentNode = Optional.<NormalizedNode<?, ?>> of(tree);
        final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
        while (currentNode.isPresent() && pathIterator.hasNext()) {
            currentNode = getDirectChild(currentNode.get(), pathIterator.next());
        }
        return currentNode;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Optional<NormalizedNode<?, ?>> getDirectChild(final NormalizedNode<?, ?> node, final PathArgument pathArg) {
        if (node instanceof LeafNode<?> || node instanceof LeafSetEntryNode<?>) {
            return Optional.absent();
        } else if (node instanceof DataContainerNode<?>) {
            return (Optional) ((DataContainerNode<?>) node).getChild(pathArg);
        } else if (node instanceof MapNode && pathArg instanceof NodeIdentifierWithPredicates) {
            return (Optional) ((MapNode) node).getChild((NodeIdentifierWithPredicates) pathArg);
        } else if (node instanceof LeafSetNode<?>) {
            return (Optional) ((LeafSetNode<?>) node).getChild((NodeWithValue) pathArg);
        }
        return Optional.absent();
    }

    /**
     * Convert a data subtree under a node into a human-readable string format.
     *
     * @param node Data subtree root
     * @return String containing a human-readable form of the subtree.
     */
    public static String toStringTree(final NormalizedNode<?, ?> node) {
        final StringBuilder builder = new StringBuilder();
        toStringTree(builder, node, 0);
        return builder.toString();
    }

    private static void toStringTree(final StringBuilder builder, final NormalizedNode<?, ?> node, final int offset) {
        final String prefix = Strings.repeat(" ", offset);

        builder.append(prefix).append(toStringTree(node.getIdentifier()));
        if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
            final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) node;

            builder.append(" {\n");
            for (NormalizedNode<?, ?> child : container.getValue()) {
                toStringTree(builder, child, offset + STRINGTREE_INDENT);
            }

            builder.append(prefix).append('}');
        } else {
            builder.append(' ').append(node.getValue());
        }
        builder.append('\n');
    }

    private static String toStringTree(final PathArgument identifier) {
        if (identifier instanceof NodeIdentifierWithPredicates) {
            StringBuilder builder = new StringBuilder();
            builder.append(identifier.getNodeType().getLocalName());
            builder.append(((NodeIdentifierWithPredicates) identifier).getKeyValues().values());
            return builder.toString();
        } else if (identifier instanceof AugmentationIdentifier) {
            return "augmentation";
        } else {
            return identifier.getNodeType().getLocalName();
        }
    }
}

@@ -546,16 +546,41 @@
 trings;%0A
+import java.util.Arrays;%0A
 import j
@@ -1852,32 +1852,41 @@
  findNode(final 
+Optional%3C
 NormalizedNode%3C?
@@ -1893,45 +1893,56 @@
 , ?%3E
- tree, final YangInstanceIdentifier p
+%3E parent, final Iterable%3CPathArgument%3E relativeP
 ath)
@@ -1969,19 +1969,23 @@
 ull(
-tree, %22Tree
+parent, %22Parent
  mus
@@ -2026,16 +2026,33 @@
 ull(
-path, %22P
+relativePath, %22Relative p
 ath 
@@ -2129,48 +2129,14 @@
 e = 
-Optional.%3CNormalizedNode%3C?, ?%3E%3E of(tree)
+parent
 ;%0A  
@@ -2189,31 +2189,20 @@
 r = 
-path.getPathArguments()
+relativePath
 .ite
@@ -2401,24 +2401,1004 @@
 ode;%0A    %7D%0A%0A
+    public static Optional%3CNormalizedNode%3C?, ?%3E%3E findNode(final Optional%3CNormalizedNode%3C?, ?%3E%3E parent, final PathArgument... relativePath) %7B%0A        return findNode(parent, Arrays.asList(relativePath));%0A    %7D%0A%0A    public static Optional%3CNormalizedNode%3C?, ?%3E%3E findNode(final NormalizedNode%3C?, ?%3E parent, final Iterable%3CPathArgument%3E relativePath) %7B%0A        return findNode(Optional.%3CNormalizedNode%3C?, ?%3E%3EfromNullable(parent), relativePath);%0A    %7D%0A%0A    public static Optional%3CNormalizedNode%3C?, ?%3E%3E findNode(final NormalizedNode%3C?, ?%3E parent, final PathArgument... relativePath) %7B%0A        return findNode(parent, Arrays.asList(relativePath));%0A    %7D%0A%0A    public static Optional%3CNormalizedNode%3C?, ?%3E%3E findNode(final NormalizedNode%3C?, ?%3E tree, final YangInstanceIdentifier path) %7B%0A        checkNotNull(tree, %22Tree must not be null%22);%0A        checkNotNull(path, %22Path must not be null%22);%0A%0A        return findNode(Optional.%3CNormalizedNode%3C?, ?%3E%3Eof(tree), path.getPathArguments());%0A    %7D%0A%0A
     @Suppres

Add more NormalizedNodes.findNode() alternatives