/**
 * 
 */
package com.planimod.ui.views.admin.position;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.window.IShellProvider;

import com.patrikdufresne.managers.ManagedObject;
import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.util.Localized;
import com.planimod.core.IntegrityException;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Position;
import com.planimod.core.Section;
import com.planimod.ui.PlanimodPolicy;
import com.planimod.ui.theme.Resources;
import com.planimod.ui.views.AbstractAddAction;

/**
 * Action to create a new Rider object and add it to the database.
 * 
 * @author dufresne
 * 
 */
public class AddPositionAction extends AbstractAddAction implements
		ISelectionChangedListener {

	/**
	 * Create a new action.
	 * 
	 * @param shellProvider
	 *            a shell provider in case the action need to display a message
	 *            box.
	 */
	public AddPositionAction(PlanimodManagers managers,
			IShellProvider shellProvider, ISelectionProvider provider) {
		super(managers, shellProvider, provider);
		setText(Localized
				.get(AddPositionAction.class, "AddPositionAction.text")); //$NON-NLS-1$
		setToolTipText(Localized.get(AddPositionAction.class,
				"AddPositionAction.tooltipText")); //$NON-NLS-1$
		setImageDescriptor(Resources
				.getImageDescriptor(Resources.ICON_LIST_ADD_16));
	}

	/**
	 * This implementation create rider object.
	 * 
	 * @throws IntegrityException
	 *             if the object can't be created for integrity reason.
	 * 
	 * @see net.ekwos.gymkhana.ui.views.AbstractAddAction#createObjects()
	 */
	@Override
	protected List<? extends ManagedObject> createObjects()
			throws IntegrityException {
		List<Section> sections;
		try {
			sections = getManagers().getSectionManager().list();
		} catch (ManagerException e) {
			PlanimodPolicy.showException(e);
			return Collections.EMPTY_LIST;
		}

		Position position = new Position();
		position.setName(Localized.get(AddPositionAction.class,
				"AddPositionAction.newPositionName")); //$NON-NLS-1$

		// Create a new section if none exists.
		if (sections.size() == 0) {
			throw new IntegrityException(Localized.get(AddPositionAction.class,
					"AddPositionAction.noSectionFound")); //$NON-NLS-1$
		}
		position.setSection(sections.get(0));
		return Arrays.asList(position);
	}

	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		// TODO Auto-generated method stub

	}

	@Override
	protected boolean canCreateObject() {
		return true;
	}

}