/*
 * 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 javax.persistence.OneToOne;
import javax.persistence.Version;

import org.apache.openjpa.jdbc.meta.FieldMapping;
import org.apache.openjpa.sdo.ImplHelper;
import org.apache.openjpa.sdo.SDOInstanceMapping;
import org.apache.openjpa.sdo.SDOMappingRepository;

import serp.bytecode.Annotations;
import serp.bytecode.BCField;

import commonj.sdo.DataObject;
import commonj.sdo.Property;

/**
 * Maps single-valued, reference Property.
 * 
 * @author Pinaki Poddar
 * @since 0.2.0
 */
public class RelationMapping extends AbstractPropertyMapping {
	
	RelationMapping(TypeMapping tm, Property p, FieldMapping fm) {
		super(tm, p, fm);
	}
	
	public String getName() {
		return "RelationMapping";
	}
	
	public String getFieldTypeName() {
		return ImplHelper.getFullClassName(property.getType());
	}
	
	public Class getFieldType(SDOMappingRepository repos) {
		return repos.getJavaClass(property.getType(), true);
	}
	
	public String[] getAnnotationStrings() {
		return new String[] {"@OneToOne"};
	}
	
	public void annotate(BCField field) {
		Annotations annos = field.getDeclaredRuntimeAnnotations(true);
		annos.addAnnotation(OneToOne.class);
	}

	public DataObject populateDataObject(DataObject target, Object source, 
			SDOInstanceMapping ctx) throws Exception {
		Object value = getter.invoke(source, NULL_ARGS);
		DataObject result = ctx.populateDataObject(value);
		target.setDataObject(property, result);
		return result;

	}

	public Object populatePC(Object pc, DataObject data, 
			SDOInstanceMapping ctx) throws Exception {
		DataObject value = data.getDataObject(property);
		Object result = ctx.populatePC(value);
		setter.invoke(pc, result);
		return result;
	}

}
