/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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 org.apache.commons.chain2.impl;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.chain2.Catalog;
import org.apache.commons.chain2.ChainUtil;
import org.apache.commons.chain2.Command;

/**
 * <p>Simple in-memory implementation of {@link Catalog}.  This class can
 * also be used as the basis for more advanced implementations.</p>
 *
 * <p>This implementation is thread-safe.</p>
 *
 * @version $Id$
 *
 * @param <K> the type of keys maintained by the context associated with this catalog
 * @param <V> the type of mapped values
 * @param <C> Type of the context associated with this catalog
 */
public class CatalogBase<K, V, C extends Map<K, V>> implements Catalog<K, V, C> {

    // ----------------------------------------------------- Instance Variables

    /**
     * <p>The map of named {@link Command}s, keyed by name.
     */
    private final Map<String, Command<K, V, C>> commands = new ConcurrentHashMap<>();

    // --------------------------------------------------------- Constructors

    /**
     * Create an empty catalog.
     */
    public CatalogBase() { }

    /**
     * <p>Create a catalog whose commands are those specified in the given <code>Map</code>.
     * All Map keys should be <code>String</code> and all values should be <code>Command</code>.</p>
     *
     * @param cmds Map of Commands.
     *
     * @exception IllegalArgumentException if <code>commands</code>
     * is <code>null</code>
     *
     * @since Chain 1.1
     */
    public CatalogBase(final Map<String, Command<K, V, C>> cmds) {
        if (cmds == null) {
            throw new IllegalArgumentException("'commands' parameter must be not null");
        }
        this.commands.putAll(cmds);
    }

    // --------------------------------------------------------- Public Methods

    /**
     * <p>Add a new name and associated {@link Command}
     * to the set of named commands known to this {@link Catalog},
     * replacing any previous command for that name.
     * @param <T> the {@link Command} type to be added in the {@link Catalog}
     * @param name Name of the new command
     * @param command {@link Command} to be returned
     *  for later lookups on this name
     */
    @Override
    public <T extends Command<K, V, C>> void addCommand(final String name, final T command) {
        this.commands.put(name, command);
    }

    /**
     * <p>Return the {@link Command} associated with the
     * specified name, if any; otherwise, return <code>null</code>.</p>
     * @param <T> the expected {@link Command} type to be returned
     * @param name Name for which a {@link Command}
     *  should be retrieved
     * @return The Command associated with the specified name.
     */
    @Override
    public <T extends Command<K, V, C>> T getCommand(final String name) {
        // it would throw ClassCastException if users try to cast to a different type
        return ChainUtil.cast(this.commands.get(name));
    }

    /**
     * Returns the map of named {@link Command}s, keyed by name.
     *
     * @return The map of named {@link Command}s, keyed by name.
     * @since 2.0
     */
    public Map<String, Command<K, V, C>> getCommands() {
        return Collections.unmodifiableMap(this.commands);
    }

    /**
     * <p>Return an <code>Stream</code> over the set of named commands
     * known to this {@link Catalog}.  If there are no known commands,
     * an empty Stream is returned.</p>
     * @return An stream of the names in this Catalog.
     */
    @Override
    public Stream<String> getNames() {
        return this.commands.keySet().stream();
    }

    /**
     * Converts this Catalog to a String.  Useful for debugging purposes.
     * @return a representation of this catalog as a String
     */
    @Override
    public String toString() {
        StringBuilder str = new StringBuilder("[").append(super.getClass().getName()).append(": ");
        str.append(getNames().collect(Collectors.joining(", ")));
        return str.append("]").toString();
    }

}
