/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.packaging;

import com.arsdigita.util.parameter.*;
import com.arsdigita.util.*;

import java.io.*;
import java.util.*;

import org.apache.commons.cli.*;

/**
 * Get
 *
 * @author Rafael H. Schloming &lt;rhs@mit.edu&gt;
 * @version $Revision: #5 $ $Date: 2004/04/07 $
 **/

class Get extends Command {

    public final static String versionId = "$Id: //core-platform/dev/src/com/arsdigita/packaging/Get.java#5 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    private static final Options OPTIONS = getOptions();

    static {
        OptionGroup group = new OptionGroup();
        group.addOption
            (OptionBuilder
             .hasArg(false)
             .withLongOpt("all")
             .withDescription("Lists all configuration parameters")
             .create());
        group.addOption
            (OptionBuilder
             .hasArg()
             .withLongOpt("value")
             .withDescription("Prints a scalar value without the key")
             .create());
        OPTIONS.addOptionGroup(group);
    }

    public Get() {
        super("get", "Print one or more values from a CCM " +
              "configuration database");
    }

    public boolean run(String[] args) {
        CommandLine line;
        try {
            line = new PosixParser().parse(OPTIONS, args);
        } catch (ParseException e) {
            System.err.println(e.getMessage());
            return false;
        }

        if (args.length == 0) {
            usage(OPTIONS, System.err, "[PARAMETERS]");
            return false;
        }

        if (line.hasOption("usage") || line.hasOption("help")) {
            usage(OPTIONS, System.out);
            return true;
        }

        ConfigRegistry reg = new ConfigRegistry();
        Config config = new Config(reg);
        config.load(System.err);

        String[] names;
        if (line.hasOption("value")) {
            names = new String[] { line.getOptionValue("value") };
            if (line.getArgs().length > 0) {
                System.err.println
                    ("--value option does not allow parameters");
                return false;
            }
        } else {
            names = line.getArgs();
        }

        List parameters;

        if (line.hasOption("all")) {
            if (names.length > 0) {
                System.err.println("--all option does not allow parameters");
                return false;
            }
            parameters = config.getParameters();
        } else {
            parameters = new ArrayList();
            boolean err = false;
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                Parameter param = config.getParameter(name);
                if (param == null) {
                    System.err.println("no such parameter: " + name);
                    err = true;
                } else {
                    parameters.add(param);
                }
            }
            if (err) { return false; }
        }

        for (Iterator it = parameters.iterator(); it.hasNext(); ) {
            Parameter param = (Parameter) it.next();
            Object value = config.get(param);
            Properties props = new Properties();
            ParameterWriter writer = new JavaPropertyWriter(props);
            param.write(writer, value);
            if (line.hasOption("value")) {
                if (props.size() > 1) {
                    System.err.println("not a scalar: " + param.getName());
                    return false;
                }
                System.out.println(props.values().iterator().next());
            } else {
                try {
                    write(props, System.out);
                } catch (IOException e) {
                    System.err.println(e.getMessage());
                    return false;
                }
            }
        }

        return true;
    }

    private void write(Properties properties, PrintStream out)
        throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        properties.store(baos, null);
        BufferedReader reader =
            new BufferedReader(new StringReader(baos.toString()));
        while (true) {
            String line = reader.readLine();
            if (line == null) { return; }
            if (line.trim().startsWith("#")) {
                continue;
            }
            out.println(line);
        }
    }

}
