//------------------------------------------------------------------------------
// 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.publishing.services;

import java.io.File;
import java.text.MessageFormat;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.epf.common.utils.Timer;
import org.eclipse.epf.publishing.PublishingPlugin;
import org.eclipse.epf.uma.MethodConfiguration;

/**
 * Abstract publishing manager class. 
 * use the org.eclipse.epf.publishing.ui.publishers extension point to extend this class 
 * if you need to customize the publishing.
 * 
 * @author Jinhua Xi
 * @since 1.0
 *
 */
public abstract class AbstractPublishManager {

	protected static boolean debug = PublishingPlugin.getDefault().isDebugging();

	protected String pubDir;
	protected MethodConfiguration config;
	protected PublishOptions options;
	protected AbstractViewBuilder viewBuilder;
	protected boolean sucess = false;


	public AbstractPublishManager() {
		
	}
	
	public void init(String pubDir, MethodConfiguration config, PublishOptions options) {
		this.pubDir = pubDir;
		
		if ( !this.pubDir.endsWith(File.separator) ) {
			this.pubDir += File.separator;
		}
		
		this.config = config;
		this.options = options;
		this.viewBuilder = createViewBuilder();
	}
	
	public AbstractViewBuilder getViewBuilder() {
		return this.viewBuilder;
	}

	public void publish(IProgressMonitor monitor) throws PublishingServiceException {
		
		if ( options != null ) {
			options.validate();
		}
		
		Timer t = null;
		if ( debug ) {
			t = new Timer();
		}
		
		try {
			
			prePublish(monitor);
			doPublish(monitor);
			postPublish(monitor);
			
			sucess = true;
		} catch (Exception e) {
			throw new PublishingServiceException(e);
		} finally {
			if (debug && t != null ) {
				
				System.out
						.println(MessageFormat
								.format(
										"Time taken to publish configuration ''{0}'': {1} secs", //$NON-NLS-1$
										new Object[] { config.getName(),
												"" + t.getTime()/1000 }));
			}
		}
	}
	
	public void dispose() {
		if ( viewBuilder != null ) {
			viewBuilder.dispose();
			viewBuilder = null;
		}
	}

	
	public abstract String getPublishedUrl();
	public abstract String getPublishReportUrl();
	
	protected abstract AbstractViewBuilder createViewBuilder();
	protected abstract void prePublish(IProgressMonitor monitor) throws Exception;
	protected abstract void doPublish(IProgressMonitor monitor) throws Exception;
	protected abstract void postPublish(IProgressMonitor monitor) throws Exception;


}
