/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2013 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.addon.commands;

import org.apache.felix.gogo.commands.Action;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.HandlerDeclaration;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.service.command.CommandSession;
import org.ow2.jonas.addon.deploy.api.deployable.IAddonDeployable;
import org.ow2.jonas.addon.deploy.api.deployable.IAddonMetadata;
import org.ow2.jonas.addon.deploy.api.deployer.IAddonService;
import org.ow2.jonas.properties.ServiceProperties;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

import java.io.File;
import java.util.Map;
import java.util.Properties;

/**
 * Show addon info
 * @author Jeremy Cazaux
 */
@Component
@Command(name="info", scope="addon", description="show addon information")
@HandlerDeclaration("<sh:command xmlns:sh='org.ow2.shelbie'/>")
public class AddonInfoCommand implements Action {

    /**
     * The logger
     */
    private static Log logger = LogFactory.getLog(AddonInfoCommand.class);

    /**
     * The name of the addon to stop
     */
    @Argument(name = "addonId", required = true, description = "Id of the Addon")
    private String addonId;

    /**
     * The {@link org.ow2.jonas.addon.deploy.api.deployer.IAddonService}
     */
    @Requires(optional = false)
    private IAddonService addonService;

    /**
     * {@inheritDoc}
     */
    @Override
    public Object execute(CommandSession commandSession) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();

        Long id = null;
        try {
            id = Long.parseLong(addonId);
        } catch (NumberFormatException e) {
            logger.error("Invalid addon id " + addonId, e);
        }
        IAddonDeployable addon = this.addonService.getAddon(id);
        if (addon != null) {
            stringBuilder.append(addon.getName());
            stringBuilder.append(" (ID ");
            stringBuilder.append(addon.getAddonId());
            stringBuilder.append(")");
            stringBuilder.append(ListAddonCommand.EOL);
            int length = addon.getName().length();
            length = length + 5 + String.valueOf(addon.getAddonId()).length();
            for (int i = 0; i < length; i++) {
                stringBuilder.append("-");
            }
            stringBuilder.append(":");
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("parent.id = ");
            IAddonDeployable parent = addon.getParent();
            if (parent != null) {
                stringBuilder.append(parent.getAddonId());
            } else {
                stringBuilder.append("none");
            }
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("state = ");
            stringBuilder.append(ListAddonCommand.getStateAsString(addon.getState()));
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("capabilities = ");
            stringBuilder.append(InspectCommand.printList(addon.getCapabilities()));
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("requirements = ");
            stringBuilder.append(InspectCommand.printList(addon.getRequirements()));
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("configuration.directory = ");
            File configurationDirectory = addon.getConfigurationDirectory();
            if (configurationDirectory != null && configurationDirectory.exists()) {
                stringBuilder.append(configurationDirectory.getAbsolutePath());
            }
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("configuration.files = ");
            stringBuilder.append(InspectCommand.printList(addon.getConfigurationFileNames()));

            IAddonMetadata metadata = addon.getMetadata();
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("jonas.service = ");
            stringBuilder.append(String.valueOf(metadata.isJOnASService()));
            stringBuilder.append(ListAddonCommand.EOL);
            if (metadata.isJOnASService()) {
                stringBuilder.append("jonas.service.name = ");
                stringBuilder.append(metadata.getService());
                stringBuilder.append(ListAddonCommand.EOL);
            }
            stringBuilder.append("metadata.autostart = ");
            stringBuilder.append(String.valueOf(metadata.getAutostart()));
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("metadata.author = ");
            stringBuilder.append(metadata.getAuthor());
            stringBuilder.append(ListAddonCommand.EOL);
            stringBuilder.append("metadata.licence = ");
            stringBuilder.append(metadata.getLicence());

            String description = metadata.getDescription();
            if (description != null && !description.isEmpty()) {
                stringBuilder.append(ListAddonCommand.EOL);
                stringBuilder.append("metadata.description = ");
                stringBuilder.append(metadata.getDescription());
            }

            String tenantId = metadata.getTenantId();
            if (tenantId != null && !tenantId.isEmpty()) {
                stringBuilder.append(ListAddonCommand.EOL);
                stringBuilder.append("metadata.tenantId = ");
                stringBuilder.append(tenantId);
            }
            String instance = metadata.getInstance();
            if (instance != null && !instance.isEmpty()) {
                stringBuilder.append(ListAddonCommand.EOL);
                stringBuilder.append("metadata.instance = ");
                stringBuilder.append(instance);
            }

            ServiceProperties serviceProperties = metadata.getServiceProperties();
            if (serviceProperties != null) {
                stringBuilder.append(ListAddonCommand.EOL);
                stringBuilder.append("metadata.properties = ");
                Properties properties = serviceProperties.getProperties();
                for (Map.Entry entry: properties.entrySet()) {
                    String key = String.valueOf(entry.getKey());
                    String value = String.valueOf(entry.getValue());
                    stringBuilder.append(ListAddonCommand.EOL);
                    stringBuilder.append("  ");
                    stringBuilder.append(key);
                    stringBuilder.append(" = ");
                    stringBuilder.append(value);
                }
            }
        } else {
            logger.error("Unable to cache addon: " + id);
        }
        return stringBuilder.toString();
    }
}
