/*
 * 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.web.servlet;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.commons.chain2.web.MapEntry;

/**
 * <p>Private implementation of <code>Map</code> for servlet context
 * attributes.</p>
 *
 * @version $Id$
 */
final class ServletApplicationScopeMap implements Map<String, Object>, Serializable {

    /** serialVersionUID */
    private static final long serialVersionUID = -6513561452066815874L;

    /** ServletContext */
    private transient ServletContext context = null;

    /**
     * Constructor
     * @param ctx ServletContext
     */
    ServletApplicationScopeMap(final ServletContext ctx) {
        this.context = ctx;
    }

    /**
     * @see java.util.Map#clear()
     */
    @Override
    public void clear() {
        for (final String key : keySet()) {
            this.context.removeAttribute(key);
        }
    }

    /**
     * @see java.util.Map#containsKey(java.lang.Object)
     */
    @Override
    public boolean containsKey(final Object key) {
        return this.context.getAttribute(toKey(key)) != null;
    }

    /**
     * @see java.util.Map#containsValue(java.lang.Object)
     */
    @Override
    public boolean containsValue(final Object value) {
        if (value != null) {
            for (final String key : Collections.list(this.context.getAttributeNames())) {
                Object next = this.context.getAttribute(key);
                if (value.equals(next)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @see java.util.Map#entrySet()
     */
    @Override
    public Set<Entry<String, Object>> entrySet() {
        Set<Entry<String, Object>> set = new HashSet<>();
        for (final String key : Collections.list(this.context.getAttributeNames())) {
            set.add(new MapEntry<>(key, this.context.getAttribute(key), true));
        }
        return set;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object o) {
        if (o != this) {
            if (!ServletApplicationScopeMap.class.isInstance(o)) {
                return false;
            }
            ServletApplicationScopeMap map = (ServletApplicationScopeMap) o;
            return this.context.equals(map.context);
        }
        return true;
    }

    /**
     * @see java.util.Map#get(java.lang.Object)
     */
    @Override
    public Object get(final Object key) {
        return this.context.getAttribute(toKey(key));
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        return this.context.hashCode();
    }

    /**
     * @see java.util.Map#isEmpty()
     */
    @Override
    public boolean isEmpty() {
        return size() < 1;
    }

    /**
     * @see java.util.Map#keySet()
     */
    @Override
    public Set<String> keySet() {
        return new HashSet<>(Collections.list(this.context.getAttributeNames()));
    }

    /**
     * @see java.util.Map#put(java.lang.Object, java.lang.Object)
     */
    @Override
    public Object put(final String key, final Object value) {
        if (value == null) {
            return remove(key);
        }
        Object previous = this.context.getAttribute(key);
        this.context.setAttribute(key, value);
        return previous;
    }

    /**
     * @see java.util.Map#putAll(java.util.Map)
     */
    @Override
    public void putAll(final Map<? extends String, ?> map) {
        for (final Entry<? extends String, ?> entry : map.entrySet()) {
            put(toKey(entry.getKey()), entry.getValue());
        }
    }

    /**
     * @see java.util.Map#remove(java.lang.Object)
     */
    @Override
    public Object remove(final Object key) {
        String skey = toKey(key);
        Object previous = this.context.getAttribute(skey);
        this.context.removeAttribute(skey);
        return previous;
    }

    /**
     * @see java.util.Map#size()
     */
    @Override
    public int size() {
        return Collections.list(this.context.getAttributeNames()).size();
    }

    /**
     * @see java.util.Map#values()
     */
    @Override
    public Collection<Object> values() {
        List<Object> list = new ArrayList<>();
        for (final String key : Collections.list(this.context.getAttributeNames())) {
            list.add(this.context.getAttribute(key));
        }
        return list;
    }

    /**
     * to Key String
     * @param key Key
     * @return Key String
     */
    private String toKey(final Object key) {
        if (key == null) {
            throw new IllegalArgumentException();
        }
        return key.toString();
    }

}
