/**
 *  Copyright 2005-2016 Red Hat, Inc.
 *
 *  Red Hat licenses this file to you 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 io.fabric8.commands;

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

import io.fabric8.api.*;
import io.fabric8.boot.commands.support.EnsembleCommandSupport;
import io.fabric8.common.util.Strings;
import io.fabric8.utils.FabricValidations;
import io.fabric8.zookeeper.bootstrap.BootstrapConfiguration;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.apache.karaf.shell.console.AbstractAction;
import org.osgi.framework.BundleContext;

@Command(name = EnsembleAdd.FUNCTION_VALUE, scope = EnsembleAdd.SCOPE_VALUE, description = EnsembleAdd.DESCRIPTION, detailedDescription = "classpath:ensembleAdd.txt")
public class EnsembleAddAction extends AbstractAction {

    @Option(name = "--generate-zookeeper-password", multiValued = false, description = "Flag to enable automatic generation of password")
    private boolean generateZookeeperPassword = false;

    @Option(name = "--new-zookeeper-password", multiValued = false, description = "The ensemble new password to use (defaults to the old one)")
    private String zookeeperPassword;

    @Option(name = "--zookeeper-ticktime", multiValued = false, description = "The length of a single tick, which is the basic time unit used by ZooKeeper, as measured in milliseconds. It is used to regulate heartbeats, and timeouts. For example, the minimum session timeout will be two ticks")
    private int zooKeeperTickTime;

    @Option(name = "--zookeeper-init-limit", multiValued = false, description = "The amount of time, in ticks (see tickTime), to allow followers to connect and sync to a leader")
    private int zooKeeperInitLimit;

    @Option(name = "--zookeeper-sync-limit", multiValued = false, description = "The amount of time, in ticks (see tickTime), to allow followers to sync with ZooKeeper")
    private int zooKeeperSyncLimit;

    @Option(name = "--zookeeper-data-dir", multiValued = false, description = "The location where ZooKeeper will store the in-memory database snapshots and, unless specified otherwise, the transaction log of updates to the database.")
    private String zooKeeperDataDir;

    @Option(name = "-f", aliases = "--force", multiValued = false, description = "Flag to force the addition without prompt")
    private boolean force = false;

    @Option(name = "--migration-timeout", multiValued = false, description = "Timeout to wait for containers to migrate to the new ensemble")
    private long migrationTimeout = CreateEnsembleOptions.DEFAULT_MIGRATION_TIMEOUT;

    @Argument(required = true, multiValued = true, description = "List of containers to be added")
    private List<String> containers;

    private final BundleContext bundleContext;
    private final ZooKeeperClusterService clusterService;
    private final FabricService fabricService;
    private final BootstrapConfiguration bootstrapConfiguration;

    EnsembleAddAction(BundleContext bundleContext, ZooKeeperClusterService clusterService, BootstrapConfiguration bootstrapConfiguration, FabricService fabricService) {
        this.bundleContext = bundleContext;
        this.clusterService = clusterService;
        this.fabricService = fabricService;
        this.bootstrapConfiguration = bootstrapConfiguration;
    }

    @Override
    protected Object doExecute() throws Exception {
        FabricValidations.validateContainerNames(containers);
        if (EnsembleCommandSupport.checkIfShouldModify(session, force)) {
            if (containers != null && !containers.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                sb.append("Adding containers:");
                for (String container : containers) {
                    sb.append(" ").append(container);
                }
                sb.append(" to the ensemble. This may take a while.");

                CreateEnsembleOptions.Builder builder = CreateEnsembleOptions.builder();
                applyEnsembleConfiguration();
                builder = builder.zooKeeperServerTickTime(zooKeeperTickTime)
                        .zooKeeperServerInitLimit(zooKeeperInitLimit)
                        .zooKeeperServerSyncLimit(zooKeeperSyncLimit)
                        .zooKeeperServerDataDir(zooKeeperDataDir)
                        .migrationTimeout(migrationTimeout);

                builder.minimumPort(bootstrapConfiguration.getBootstrapOptions().getMinimumPort());
                builder.maximumPort(bootstrapConfiguration.getBootstrapOptions().getMaximumPort());

                if (generateZookeeperPassword) {
                    //Don't add password
                } else if (zookeeperPassword == null || zookeeperPassword.isEmpty()) {
                    builder = builder.zookeeperPassword(clusterService.getZookeeperPassword());
                } else {
                    builder = builder.zookeeperPassword(zookeeperPassword);
                }

                if(force){
                    List<String> current = clusterService.getEnsembleContainers();
                    Container[] allExistingContainers = fabricService.getContainers();

                    // filter out deleted containers from the ensemble list
                    List<String> filtered = new ArrayList<>(current.size());
                    for(String ensembleMember : current){
                        for(Container existing : fabricService.getContainers()){
                            if(existing.getId().equals(ensembleMember)){
                                filtered.add(ensembleMember);
                            }
                        }
                    }
                    current = filtered;
                    for (String c : this.containers) {
                    	// let's add it only if it wasn't already there
                    	if (!current.contains(c)) {
                            current.add(c);
                    	}
                    }
                    clusterService.createCluster(current, builder.build());
                } else{
                    // checks for presence of the container in the ensemble and prevents it addition
                    clusterService.addToCluster(containers, builder.build());
                }

                ServiceProxy<ZooKeeperClusterService> serviceProxy = ServiceProxy.createServiceProxy(bundleContext, ZooKeeperClusterService.class);
                try {
                    System.out.println("Updated Zookeeper connection string: " + serviceProxy.getService().getZooKeeperUrl());
                } finally {
                    serviceProxy.close();
                }
            }
        }
        return null;
    }

    private void applyEnsembleConfiguration() throws Exception {
        Map<String, String> currentConfig = clusterService.getEnsembleConfiguration();
        int currentTickTime = Integer.parseInt(currentConfig.get("tickTime"));
        int currentInitLimit = Integer.parseInt(currentConfig.get("initLimit"));
        int currentSyncLimit = Integer.parseInt(currentConfig.get("syncLimit"));
        String currentDataDir = currentConfig.get("dataDir");       
        int lastIndexOfFwdSlash = currentDataDir.lastIndexOf("/"); // prefer fwd slash        
        currentDataDir = currentDataDir.substring(0, (lastIndexOfFwdSlash < 0) ? currentDataDir.lastIndexOf("\\") : lastIndexOfFwdSlash);

        zooKeeperTickTime = zooKeeperTickTime != 0 ? zooKeeperTickTime : currentTickTime;
        zooKeeperInitLimit = zooKeeperInitLimit != 0 ? zooKeeperInitLimit : currentInitLimit;
        zooKeeperSyncLimit = zooKeeperSyncLimit != 0 ? zooKeeperSyncLimit : currentSyncLimit;
        zooKeeperDataDir = !Strings.isNullOrBlank(zooKeeperDataDir) ? zooKeeperDataDir : currentDataDir;
    }

}
