/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * 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 com.queplix.core.integrator.security;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Contains set of the permissions.
 *
 * @author Sergey Kozmin
 * @since 16.01.2007
 */
public class PermissionSet implements Iterable<Permission> {

    public final static PermissionSet EMPTY = new PermissionSet();

    /**
     * Access object id to permission
     */
    private Map<String, Permission> permissions
            = new HashMap<String, Permission>();

    void addPermission(Permission perm) {
        permissions.put(getKey(perm.getObjectType(), perm.getObjectID()), perm);
    }

    void addAllPermissions(Collection<Permission> col) {
        for(Permission aCol : col) {
            addPermission(aCol);
        }
    }

    void addPermissionSet(PermissionSet permissionSet) {
        for(Permission permission : permissionSet) {
            addPermission(permission);
        }
    }

    /**
     * Retrieve permissions for the object
     *
     * @param type object type
     * @param id   permission object
     * @return permission object, if object is null it means there is no permission
     */
    public Permission getPermissionObject(PermissionObjectType type,
                                          String id) {
        return permissions.get(getKey(type, id));
    }

    public Iterator<Permission> iterator() {
        return permissions.values().iterator();
    }

    public boolean isEmpty() {
        return permissions.isEmpty();
    }

    private String getKey(PermissionObjectType type, String id) {
        return type.getStringRepr() + "_" + id;
    }

}
