/*
 * 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.openjpa.sdo.mapping;

import org.apache.openjpa.jdbc.meta.FieldMapping;
import org.apache.openjpa.sdo.ImplHelper;

import commonj.sdo.Property;
import commonj.sdo.Type;

/**
 * Decides appropariate mapping strategy for any given Property.
 * 
 * @author Pinaki Poddar
 * @since 0.2.0
 */
public class SDOMappingStrategy {
	/**
	 * Decides the mapping strategy  to be used for the given Type.
	 *  
	 * @param type the Type  to be mapped.
	 * @param cmd The class with database mapping information. This is
	 * null i.e. not available during code generation and available
	 * during runtime.
	 * 
	 * @return the mapping to be used for the given Type.
	 */
	public static TypeMapping decideStrategy(Type type, Class cls) {
		return new IdenticalTypeMapping(type, cls);
	}
	
	/**
	 * Decides the mapping strategy to be used for the given Property.
	 * 
	 * @param p the Property to be mapped.
	 * @param fmd The field with database mapping information. This is
	 * null i.e. not available during code generation and available
	 * during runtime.
	 * 
	 * @return the mapping to be used for the given Property.
	 * 
	 */
	public static PropertyMapping decideStrategy(TypeMapping tm, Property p, FieldMapping fmd) {
		if (ImplHelper.isIdentity(p))
			return new IdentityMapping(tm, p, fmd);
		if (ImplHelper.isVersion(p))
			return new VersionMapping(tm, p, fmd);

		if (p.getType().isDataType()) {
			if (p.isMany()) {
				return new PrimitiveListMapping(tm, p, fmd);
			} else {
				return new PrimitiveMapping(tm, p, fmd);
			}
		}
		if (ImplHelper.isContainer(p.getType())) {
			Type componentType = ImplHelper.getComponentType(p.getType());
			if (componentType.isDataType())
				return new PrimitiveListMapping(tm, p, fmd);
			else
				return new RelationListMapping(tm, p, fmd);
		}
		if (p.isMany()) {
			return new RelationListMapping(tm, p, fmd);
		} else {
			return new RelationMapping(tm, p, fmd);
		}
	}
}
