//------------------------------------------------------------------------------
// 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.persistence.migration;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.epf.common.html.HTMLFormatter;
import org.eclipse.epf.uma.MethodElement;

/**
 * Utility class to help migrate and format the html content.
 * 
 * @author JInhua Xi
 * @since 1.0
 */
public class MigrationUtil {

	public static Set cdataFeatureNames = new HashSet();
	static {
		cdataFeatureNames.add("alternatives"); //$NON-NLS-1$
		cdataFeatureNames.add("mainDescription"); //$NON-NLS-1$
		cdataFeatureNames.add("howToStaff"); //$NON-NLS-1$
		cdataFeatureNames.add("keyConsiderations"); //$NON-NLS-1$
		cdataFeatureNames.add("purpose"); //$NON-NLS-1$
		cdataFeatureNames.add("scope"); // ProcessDescription //$NON-NLS-1$
		cdataFeatureNames.add("usageNotes"); // ProcessDescription //$NON-NLS-1$
	}

	private static boolean isHtmlFeature(EStructuralFeature f) {
		return cdataFeatureNames.contains(f.getName());
	}

	public static void formatValue(MethodElement element) throws Exception {
		List properties = element.getInstanceProperties();
		if (properties != null) {
			// get all string type attributes

			HTMLFormatter formater = new HTMLFormatter();

			for (int i = 0; i < properties.size(); i++) {
				EStructuralFeature feature = (EStructuralFeature) properties
						.get(i);

				Object value = element.eGet(feature);
				Object newValue = value;
				if (isHtmlFeature(feature) && value instanceof String) {
					try {
						newValue = formater.formatHTML((String) value);
					} catch (Exception e) {
						// Not change value if it cannot be formatted
						// Should also write to log for user attention
						continue;
					}
					element.eSet(feature, newValue);
				}
			}
		}
	}

}
