package com.tandbergtv.watchpoint.pmm.title;

import java.util.Collection;

import com.tandbergtv.metadatamanager.model.Asset;
import com.tandbergtv.metadatamanager.model.Field;
import com.tandbergtv.metadatamanager.model.Group;
import com.tandbergtv.metadatamanager.model.Item;
import com.tandbergtv.watchpoint.pmm.core.PMMException;
import com.tandbergtv.watchpoint.pmm.entities.Title;

/**
 * Class for Title specific utility methods.
 * 
 * @author Raj Prakash
 */
public class TitleUtil {
	
	/**
	 * For titles that are found in src, if found in dest, replaces metadata
	 * and if not found in dest, creates a new title with metadata from corresponding src title.
	 * 
	 * For titles that are found in dest and not in src, clear metadata.
	 * 
	 * @throws PMMException	when a title with a mapped asset has to be removed 
	 */
	@Deprecated
	public static void replaceMetadata(Title src, Title dest) throws PMMException {
		//TODO
		/*
		overwriteMetadata(src, dest);
		clearMetadataForDeletedTitles(src, dest);
		*/
	}
	
	/**
	 * Given a list of fields, returns the value of the first field found with the given name
	 * and the section(if any)
	 * 
	 * @param fields
	 * @param fieldName
	 * @param sectionName
	 * @return
	 */
	public static String getMetadataValue(Collection<Field> fields,
			String fieldName, String sectionName) {
		for (Field f : fields) {
			// if ttvxpath and section name both match only then return the
			// value.
			if (f.getTtvXPath().equalsIgnoreCase(fieldName)) {
				// if section name is provided check for that as well.
				if ((sectionName != null && sectionName.trim().length() > 0)) {
					if (getParentAssetType(f).equalsIgnoreCase(sectionName)) {
						return f.getValue();
					}
				} else {
					return f.getValue();
				}
			}
		}
		return "";
	}
	
	private static String getParentAssetType(Field field) {
		Asset parentAsset = field.getParentAsset();
		if (parentAsset instanceof Group) {
			return ((Group) parentAsset).getType().toString();
		} else if (parentAsset instanceof Item) {
			return ((Item) parentAsset).getType().toString();
		}
		return null;
	}
}
