001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.shell.automation;
018
019import java.util.Collections;
020import java.util.List;
021
022import jline.Completor;
023
024import org.nuxeo.ecm.automation.client.model.OperationDocumentation;
025import org.nuxeo.shell.Shell;
026
027/**
028 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
029 */
030public class ChainCompletor implements Completor {
031
032    protected RemoteContext ctx;
033
034    public ChainCompletor() {
035        this(Shell.get().getContextObject(RemoteContext.class));
036    }
037
038    public ChainCompletor(RemoteContext ctx) {
039        this.ctx = ctx;
040    }
041
042    @SuppressWarnings({ "rawtypes", "unchecked" })
043    public int complete(String buffer, int cursor, List clist) {
044        if (buffer == null) {
045            buffer = "";
046        }
047        for (OperationDocumentation op : ctx.getSession().getOperations().values()) {
048            if ("Chain".equals(op.category)) {
049                if (op.id.startsWith(buffer)) {
050                    clist.add(op.id);
051                }
052            }
053        }
054        if (clist.isEmpty()) {
055            return -1;
056        }
057        if (clist.size() == 1) {
058            return 0;
059        }
060        Collections.sort(clist);
061        return 0;
062    }
063}