//------------------------------------------------------------------------------
// 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.authoring.ui.util;

import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.epf.common.serviceability.MsgBox;
import org.eclipse.epf.common.utils.StrUtil;
import org.eclipse.epf.library.edit.LibraryEditResources;
import org.eclipse.epf.library.edit.util.MethodElementUtil;
import org.eclipse.epf.library.edit.util.TngUtil;
import org.eclipse.epf.library.edit.validation.IValidator;
import org.eclipse.epf.library.edit.validation.internal.ContentElementNameValidator;
import org.eclipse.epf.library.edit.validation.internal.ValidatorFactory;
import org.eclipse.epf.library.ui.LibraryUIText;
import org.eclipse.epf.uma.ContentElement;
import org.eclipse.epf.uma.Deliverable;
import org.eclipse.epf.uma.Guidance;
import org.eclipse.epf.uma.MethodElement;
import org.eclipse.epf.uma.Practice;
import org.eclipse.epf.uma.UmaPackage;
import org.eclipse.epf.uma.VariabilityElement;
import org.eclipse.epf.uma.WorkProduct;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;


/**
 * @author Shilpa Toraskar
 * @author Phong Nguyen Le
 * @since 1.0
 */
public class UIHelper {

	/**
	 * Setting items in a table
	 * 
	 * @param table
	 * @param items
	 */
	public static void setItems(Table table, ArrayList items) {
		table.removeAll();
		for (int i = 0; i < items.size(); i++) {
			TableItem item = new TableItem(table, SWT.NONE);
			item.setText((String) items.get(i));
		}
	}

	public static List createList(FormToolkit toolkit, Composite parent,
			int style) {
		List list = new List(parent, style | SWT.NULL);
		toolkit.adapt(list, true, true);
		return list;
	}

	/*
	 * Method will return Object[] of guidance excluding Practice.
	 * MethodElementUtil#getSelectedGuidances(EObject) calculates all guidance.
	 */
	public static Object[] getSelectedGuidances(ContentElement contentElement) {
		java.util.List list = MethodElementUtil
				.getSelectedGuidances(contentElement);
		for (Iterator it = list.iterator(); it.hasNext();) {
			Object obj = it.next();
			if (obj instanceof Practice)
				it.remove();
		}
		return list.toArray();
	}

	private static String getFormPageTitlePrefixFor(MethodElement methodElement) {
		String elementLabel = LibraryUIText.getUIText(methodElement);
		if (methodElement instanceof WorkProduct) {
			return LibraryUIText.TEXT_WORK_PRODUCT + " (" + elementLabel + ")"; //$NON-NLS-1$ //$NON-NLS-2$
		} else if (methodElement instanceof Guidance) {
			return LibraryUIText.TEXT_GUIDANCE + " (" + elementLabel + ")"; //$NON-NLS-1$ //$NON-NLS-2$
		} else {
			return elementLabel;
		}
	}

	/**
	 * Sets text for the given form based on the given element, including variable information of the element
	 * if there is any.
	 * 
	 * @param form
	 * @param element
	 */
	public static void setFormText(ScrolledForm form, MethodElement element) {
		if (form != null && !form.isDisposed()) {
			StringBuffer str = new StringBuffer();
			str.append(getFormPageTitlePrefixFor(element) + ": "); //$NON-NLS-1$
			if(element instanceof VariabilityElement) {
				str.append(TngUtil.getLabel((VariabilityElement) element,
						"", true)); //$NON-NLS-1$
			}
			else if(element.getName() != null){
				str.append(element.getName());
			}
			form.setText(str.toString());
		}
	}

	public static boolean checkCircularDeliverables(Deliverable toBePart,
			Deliverable deliverable) {
		java.util.List deliverables = toBePart.getDeliveredWorkProducts();
		if (deliverables != null && deliverables.size() > 0) {
			if (deliverables.contains(deliverable))
				return false;
			for (Iterator iterator = deliverables.iterator(); iterator
					.hasNext();) {
				Object obj = iterator.next();
				if (obj instanceof Deliverable) {
					return checkCircularDeliverables((Deliverable) obj,
							deliverable);
				}
			}
		}
		return true;
	}

	public static void deliverablePartsChain(Deliverable e, java.util.List roots) {
		java.util.List list = e.getDeliveredWorkProducts();
		if (list != null && list.size() > 0) {
			for (Iterator iterator = list.iterator(); iterator.hasNext();) {
				Object obj = iterator.next();
				if (obj instanceof Deliverable) {
					roots.add(obj);
					deliverablePartsChain((Deliverable) obj, roots);
				}
			}
		}
	}
	
	/**
	 * @param oldGuidance
	 * @param newGuidance
	 * @return
	 */
	public static String resolveContentElementNameConflict(EObject container, MethodElement element, EReference
			reference) {
		// TODO Auto-generated method stub
		final IValidator validator = new ContentElementNameValidator(container
				, reference,
				(ContentElement) element, new ValidatorFactory.TypeFilter(element));
		
		String msg = validator.isValid(element.getName());
		
		if (msg != null) {
			String featureTxt = TngUtil.getFeatureText(UmaPackage.eINSTANCE
					.getNamedElement_Name());
			String title = LibraryEditResources.resolveNameConflictDialog_title; //$NON-NLS-1$			
			String dlgMsg = NLS.bind(
					LibraryEditResources.resolveNameConflictDialog_text,
					StrUtil.toLower(featureTxt), element.getName());
			String currentValue = (String) element.eGet(UmaPackage.eINSTANCE
					.getNamedElement_Name());

			IInputValidator inputValidator = new IInputValidator() {
				public String isValid(String newText) {
					return validator.isValid(newText);
				}
			};

			InputDialog inputDlg = new InputDialog(
					MsgBox.getDefaultShell(), title, dlgMsg, currentValue,
					inputValidator);
			if (inputDlg.open() == Window.CANCEL) {
				throw new OperationCanceledException();
			}
			return inputDlg.getValue();
		}
		return null;
	}
}
