/**
 * Copyright 2008-2009 DRIVER PROJECT (ICM UW)
 * Original author: Marek Horst
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dnetlib.data.index.ws.dataprov;

import java.util.Iterator;
import java.util.List;

import eu.dnetlib.data.index.dmf.DMFObject;
import eu.dnetlib.data.index.dmf.DMFObjectBuilder;

import pl.edu.icm.yadda.service.search.searching.ResultField;
import pl.edu.icm.yadda.service.search.searching.SearchResult;

/**
 * YIS search result parser.
 * @author mhorst
 *
 */
public class SearchResultParser {

	/**
	 * Parses SearchResult to DMF document.
	 * @param searchResult
	 * @return DMF document
	 */
	public static String parseToDMF(SearchResult searchResult) {
		DMFObject dmfObject = DMFObjectBuilder.buildDMFObject(searchResult);
		if (dmfObject==null)
			return null;
		else
			return dmfObject.getAsXML();
	}
	
	/**
	 * Parses SearchResult to simple xml format.
	 * @param searchResult
	 * @return xml fields representation
	 */
	public static String parseToXMLFields(SearchResult searchResult) {
		if (searchResult==null)
			return null;
		StringBuffer strBuff = new StringBuffer();
		List<ResultField> fields = searchResult.getFields();
		Iterator<ResultField> it = fields.iterator();
		while (it.hasNext()) {
			ResultField currentField = it.next();
			if (currentField.getValues()!=null && 
					currentField.getValues().length>0) {
				for (int i = 0; i < currentField.getValues().length; i++) {
					strBuff.append('<' + currentField.getName() + '>');
					strBuff.append(currentField.getValues()[i]);
					strBuff.append("</" + currentField.getName() + '>');
				}
			}
		}
		return strBuff.toString();
	}
}
