package org.eclipse.epf.xml.uma.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.xmi.XMLHelper;
import org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl;
import org.eclipse.epf.common.serviceability.VersionUtil;

/**
 * This class customize the XMLSaveImpl to save the string tags as CDATA
 * 
 * @author Jinhua Xi
 * @since 1.0
 *
 */
public class UmaXMLSaveImpl extends XMLSaveImpl {

	public static List cdataFeatureNames = new ArrayList();
	static {
		
		cdataFeatureNames.add("alternatives");
		cdataFeatureNames.add("mainDescription");
		cdataFeatureNames.add("howToStaff");
		cdataFeatureNames.add("keyConsiderations");
		cdataFeatureNames.add("purpose");	
		cdataFeatureNames.add("scope");					// ProcessDescription
		cdataFeatureNames.add("usageNotes");			// ProcessDescription
	}
	
	private boolean isCDATAFeature(EStructuralFeature f, boolean isAttribute) {
		
		if ( isAttribute ) {
			return false;
		}
		
//		if ( f == UmaPackage.eINSTANCE.getContentDescription_KeyConsiderations() 
//			|| f == UmaPackage.eINSTANCE.getContentDescription_MainDescription()
//			|| f == UmaPackage.eINSTANCE.getSection_Description()
//		) {
//			System.out.println("test");
//		}
		
		return cdataFeatureNames.contains(f.getName());
	}
	
	public UmaXMLSaveImpl(XMLHelper helper) {
		super(helper);
	}

	public UmaXMLSaveImpl(Map options, XMLHelper helper, String encoding) {
		super(options, helper, encoding);
	}

	protected String getDatatypeValue(Object value, EStructuralFeature f,
			boolean isAttribute) {	
		
		if ( value == null || value.toString().equals("") ) {
			return "";
		}
		
		if ( isCDATAFeature(f, isAttribute) ) {
			return "<![CDATA[" + value.toString() + "]]>";
		}
		
		return super.getDatatypeValue(value, f, isAttribute);
	}
	
	public void addNamespaceDeclarations() {
		super.addNamespaceDeclarations();
		for (Iterator iter = VersionUtil.getAllToolIDs().iterator();iter.hasNext();) {
			String toolID = (String)iter.next();
			String toolVersion = VersionUtil.getVersions(toolID).getMinToolVersionForCurrentXMLSchemaVersion().getToolVersion().toString();
			doc.addAttribute(toolID + ":version", toolVersion); //$NON-NLS-1$
		}
	}
}
