package net.sourceforge.rtf.context;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import net.sourceforge.rtf.context.fields.RTFContextBookmark;
import net.sourceforge.rtf.context.fields.RTFContextFields;
import net.sourceforge.rtf.context.fields.RTFContextField;

import org.xml.sax.SAXException;

/**
 * Description : Manage RTF context object for fields XML available.
 * @version 1.0.0
 * @author <a href="mailto:angelo.zerr@gmail.com">Angelo ZERR</a>
 * 
 */
public class RTFContextUtil {

	/**
	 * return true if objectType is list and false otherwise
	 * 
	 * @param objectType
	 * @return
	 */
	public static boolean isList(Object o) {
		return o instanceof Collection;
	}



	// ///////// SAVE XML FIELDS

	public static void saveXmlFields(String fileXmlFields, RTFContextFields newFields, boolean force)
			throws SAXException, IOException {
		saveXmlFields(fileXmlFields, newFields, fileXmlFields, force);
	}

	public static void saveXmlFields(String inFileXmlFields, RTFContextFields newFields,
			String outFileXmlFields, boolean force) throws SAXException, IOException {
		if (!force) {
			// file must be updated, test if file exist
			File inFile = new File(inFileXmlFields);
			if (inFile.exists()) {
				// File exist, use digester to get RTFContextFields
				RTFContextFields oldFields = DigesterRTFContextFields
						.getRTFContextFields(inFile);
				// Get the description of the fields
				newFields.setDescription(oldFields.getDescription());
				// Get the map of the source XML fields
				Map oldContextFieldsMap = oldFields.getMergeFieldsMap();
				// Loop for New ContextFields
		    	for (Iterator iter = newFields.getMergeFields().iterator(); iter.hasNext();) {
		    		RTFContextField newField = (RTFContextField) iter.next();
		    		// Test if oldContextFieldsMap contains this field
		    		RTFContextField oldField = (RTFContextField)oldContextFieldsMap.get(newField.getName());
		    		if (oldField != null) {
		    			// Update description
		    			newField.setDescription(oldField.getDescription());
		    		}
		    	}
				// Get the map of the source XML fields
				Map oldContextBookmarksMap = oldFields.getBookmarksMap();
				// Loop for New ContextFields
		    	for (Iterator iter = newFields.getBookmarks().iterator(); iter.hasNext();) {
		    		RTFContextBookmark newBookmark = (RTFContextBookmark) iter.next();
		    		// Test if oldContextFieldsMap contains this bookmark
		    		RTFContextBookmark oldBookmark = (RTFContextBookmark)oldContextBookmarksMap.get(newBookmark.getType());
		    		if (oldBookmark != null) {
		    			// Update description of Bookmark
		    			newBookmark.setDescription(oldBookmark.getDescription());
		    		}
		    	}
			}
		}
		newFields.toXml(outFileXmlFields);
	}
}
