/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.karaf.cellar.shell.group;

import org.apache.karaf.cellar.core.Group;
import org.apache.karaf.cellar.core.Node;
import org.apache.karaf.cellar.core.control.ManageGroupAction;
import org.apache.karaf.cellar.core.control.ManageGroupResult;
import org.apache.karaf.cellar.core.shell.completer.AllNodeCompleter;
import org.apache.karaf.cellar.shell.SimpleGroupTree;
import org.apache.karaf.cellar.shell.SimpleGroupTree.GroupNode;
import org.apache.karaf.cellar.shell.SimpleGroupTree.SimpleGroupTreeHelper;
import org.apache.karaf.cellar.shell.SimpleGroupTree.SimpleGroupTreeNode;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.Option;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.support.table.ShellTable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Command(scope = "cluster", name = "group-list", description = "List the cluster groups")
@Service
public class GroupListCommand extends GroupSupport {

    @Argument(index = 0, name = "node", description = "The node(s) ID or alias", required = false, multiValued = true)
    @Completion(AllNodeCompleter.class)
    List<String> nodes;

    @Option(name = "-h", aliases = "--hierarchy-tree")
    boolean showTree = false; 
    
    @Override
    protected Object doExecute() throws Exception {
    	if (!showTree) {
    		doExecute(ManageGroupAction.LIST, null, null, nodes,false);
    		return null;
    	} else {
    		@SuppressWarnings("unchecked")
			Map<Node, ManageGroupResult> results = (Map<Node, ManageGroupResult>) doExecute(ManageGroupAction.LIST, null, null, nodes,true);
    		
            if (results == null || results.isEmpty()) {
                System.out.println("No result received within given timeout");
            } else {
                ShellTable table = new ShellTable();
                table.column(" ");
                table.column("Group");
                table.column("Parent");
                table.column("Built-In");
                table.column("Members");
                
                SimpleGroupTree<SimpleGroupTree.GroupNode> tree = new SimpleGroupTree<>(new SimpleGroupTree.GroupTreeHelper() );
                List<SimpleGroupTree.GroupNode> groupNodes = new ArrayList<>();
                
                for (Node node : results.keySet()) {
                    ManageGroupResult result = results.get(node);
                    if (result != null && result.getGroups() != null) {
                        for (Group g : result.getGroups()) {
                            StringBuffer buffer = new StringBuffer();
                            if (g.getNodes() != null && !g.getNodes().isEmpty()) {
                                String local = "";
                                for (Node member : g.getNodes()) {
                                    // display only up and running nodes in the cluster
                                    if (clusterManager.findNodeById(member.getId()) != null) {
                                        if (member.getAlias() != null) {
                                            buffer.append(member.getAlias());
                                        } else {
                                            buffer.append(member.getId());
                                        }
                                        if (member.equals(clusterManager.getNode())) {
                                            local = "x";
                                            buffer.append("(x)");
                                        }
                                        buffer.append(" ");
                                    }
                                }
                                
                                SimpleGroupTree.GroupNode groupNode = new SimpleGroupTree.GroupNode();
                                groupNode.group = g;
                                groupNode.nodesString = buffer.toString();
                                groupNode.isLocal = !local.isBlank();
                                
                                groupNodes.add(groupNode);
                                
                                // table.addRow().addContent(local, g.getName(), g.getParent(), g.isBuiltIn()?"*":"", buffer.toString());
                            } else {
                            	// table.addRow().addContent("", g.getName(), g.getParent(), g.isBuiltIn()?"*":"", "");
                                SimpleGroupTree.GroupNode groupNode = new SimpleGroupTree.GroupNode();
                                groupNode.group = g;
                                groupNode.nodesString = "";
                                groupNode.isLocal = false;
                                
                                groupNodes.add(groupNode);
                            	
                            }
                        }
                    }
                }
                
                tree.load(groupNodes);
                for (SimpleGroupTreeNode<GroupNode> grN: tree.root.children)
                	addRowToTable(table, grN);
                
                table.print(System.out);
            }
    		
    		
    		return null;
    	}
    }
    
    protected String getLevelPrefix(SimpleGroupTreeNode<GroupNode> node) {
        String result = "";
        for (int i = 0; i < node.getLevel() - 1; i++)
            result = result.concat("  ");
        return result;
    }
    
    protected void addRowToTable(ShellTable table, SimpleGroupTreeNode<GroupNode> node) {
        if (node.getObject() != null) {
            GroupNode groupNode = node.getObject();
            
            String parent = node.getObject().group.getParent();
            String parentString = (parent == null || parent.isBlank()?"":(groupManager.findGroupByName(parent)==null?" ? ":"") + parent);
            
            table.addRow().addContent(
            		groupNode.isLocal?"X":"",
                        getLevelPrefix(node) + node.getObject().group.getName(),
                        parentString,
                        node.getObject().group.isBuiltIn()?"x":"",
                        		node.getObject().nodesString);
        }
        for (SimpleGroupTreeNode<GroupNode> child : node.children) {
            addRowToTable(table, child);
        }
    }

}
