//------------------------------------------------------------------------------
// Copyright (c) 2005, 2006 IBM Corporation and others.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// Contributors:
// IBM Corporation - initial implementation
//------------------------------------------------------------------------------
package org.eclipse.epf.dataexchange.util;

import java.io.File;

import org.eclipse.epf.library.util.ResourceHelper;

/**
 * content resource handler to process the respources in the content
 * 
 * @author Jinhua Xi
 * @since 1.0
 *
 */
public abstract class BaseResourceHandler implements IResourceHandler {

	// two options to copy the resources
	// 1. reserve the resource path relative to the lib root. 
	//    This will need to change the url since the element in the target library is loacated based on element type
	// 2. make the resource path relative to the owner element, 
	//    so the resouces will be copied to the sub-folders under the owner element
	//    the url path is unchanged.
	private static final boolean reserveResourcepath = true;  // true for option 1 and false for option 2

	protected File sourceLibRoot;
	protected File targetLibRoot;

	public BaseResourceHandler(File sourceLibRoot, File targetLibRoot) {
		this.sourceLibRoot = sourceLibRoot;
		this.targetLibRoot = targetLibRoot;
	}
	
	public UrlInfo resolveFileUrl(Object owner, String srcUrl) {
		if ( reserveResourcepath ) {
			return loadUrlInfoWithFixedPath(owner, srcUrl);
		} else {
			return loadUrlInfoWithRelativePath(owner, srcUrl);			
		}
	}
	
	/**
	 * copying the resource file from the source library to the target
	 * 
	 * @param sourceFile the file path relative to the source root
	 */
	public void copyResource(String sourceFile) {
		File src = new File(sourceLibRoot, sourceFile);
		if ( src.exists() ) {
			File tgt = new File(targetLibRoot, sourceFile);
			ResourceHelper.copyFile(src, tgt);
		}
	}
	
	/**
	 * the resource path will be relative to the libary root. urls needs to be fixed
	 * 
	 * @param owner
	 * @param srcUrl
	 * @return
	 */
	protected abstract UrlInfo loadUrlInfoWithFixedPath(Object owner, String srcUrl);

	/**
	 * the resource path will be relative to the owner element. 
	 * urls will not be changed but resource files is relicated.
	 * @param owner
	 * @param srcUrl
	 * @return
	 */
	protected abstract UrlInfo loadUrlInfoWithRelativePath(Object owner, String srcUrl);

}
