/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.kernel;


import com.arsdigita.persistence.SessionManager;
import com.arsdigita.persistence.metadata.ObjectType;
import com.arsdigita.persistence.metadata.Property;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Metadata Utilities:
 * Package-private class containing utility/convenience methods for
 * accessing persistence metadata.
 **/
class MDUtil {

    // map used to cache metadata lookups
    //   - The key is an ObjectType.
    //   - The value is a Property that is the composite role for
    //     the ObjectType.
    private static HashMap s_composites = new HashMap();

    static final String PACKAGE_INSTANCE = "packageInstance";

    static Property getCompositeRole(ObjectType type) {
        if (s_composites.containsKey(type)) {
            return (Property) s_composites.get(type);
        }
        Iterator properties = type.getProperties();
        while (properties.hasNext()) {
            Property prop = (Property) properties.next();
            if (prop.isRole() &&
                prop.isRequired() &&
                !prop.isCollection()) {

                // The property is a role of multiplcity 1..1.  Now we
                // have to figure out if it is a composite role.

                if (prop.isComposite() &&
                    prop.getType() instanceof ObjectType &&
                    ((ObjectType)prop.getType())
                    .isSubtypeOf(ACSObject.BASE_DATA_OBJECT_TYPE)) {
                    s_composites.put(type, prop);
                    return prop;
                }
            }
        }
        s_composites.put(type, null);
        return null;
    }


    static boolean hasPackageInstanceRole(ObjectType o) {
        Property p = o.getProperty(PACKAGE_INSTANCE);
        return
            p != null &&
            p.isRole() &&
            ((ObjectType) p.getType()).isSubtypeOf(
                getType(PackageInstance.BASE_DATA_OBJECT_TYPE));
    }


    /**
     * convenience wrapper around
     * SessionManager.getMetadataRoot().getObjectType()
     **/
    static ObjectType getType(String typeName) {
        return SessionManager.getMetadataRoot().getObjectType(typeName);
    }
}
