package com.planimod.ui.views.employees;

import java.util.List;

import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.window.IShellProvider;

import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.printing.IPrintFactory;
import com.patrikdufresne.printing.PrintAction;
import com.patrikdufresne.util.Localized;
import com.planimod.core.ApplicationSetting;
import com.planimod.core.EmployeePreference;
import com.planimod.core.PlanimodManagers;
import com.planimod.ui.PlanimodPolicy;
import com.planimod.ui.preference.PlanimodPreferences;
import com.planimod.ui.printing.PlanimodPrintFactory;

/**
 * This action intend to print a list of Employee.
 * 
 * @author patapouf
 * 
 */
public class EmployeeBySeniorityPrintAction extends PrintAction {
	/**
	 * Define the preference key for this action
	 */
	private static final String PREF_KEY = "EmployeeBySeniorityPrintAction.printPreference"; //$NON-NLS-1$

	/**
	 * Managers to use.
	 */
	private PlanimodManagers managers;

	/**
	 * Create a new Print Employee Action
	 * 
	 * @param shell
	 *            A Shell provider used to create new windows
	 * @param operation
	 *            type of operation : PRINT or PREVIEW
	 */
	public EmployeeBySeniorityPrintAction(PlanimodManagers managers,
			IShellProvider shell, int operation, IRunnableContext context) {
		super(shell, new EmployeeBySeniorityPrintFactory(), operation, context);
		if (managers == null) {
			throw new NullPointerException();
		}
		this.managers = managers;
		setPrefKey(PREF_KEY);
		setPreferenceStore(PlanimodPreferences.getPreferenceStore());
		setEnabled(true);
		if (operation == PrintAction.PRINT_ACTION) {
			setText(Localized.get(EmployeeBySeniorityPrintAction.class,
					"EmployeeBySeniorityPrintAction.print"));//$NON-NLS-1$
		} else {
			setText(Localized.get(EmployeeBySeniorityPrintAction.class,
					"EmployeeBySeniorityPrintAction.preview"));//$NON-NLS-1$
		}

	}

	/**
	 * Returns the managers used by this action.
	 * 
	 * @return
	 */
	protected PlanimodManagers getManagers() {
		return this.managers;
	}

	/**
	 * This implementation set the employee to print
	 * 
	 * @param factory
	 *            the factory
	 */
	@Override
	protected void initFactory(IPrintFactory factory) {
		try {
			// Sets subtitle
			String custonerName = getManagers().getApplicationSettingManager()
					.getByName(ApplicationSetting.CUSTOMER_NAME);
			((PlanimodPrintFactory) factory).setSubTitle(custonerName);

			// Sets employees
			List<EmployeePreference> employees = getManagers()
					.getEmployeePreferenceManager().list();
			((EmployeeBySeniorityPrintFactory) factory).setEmployees(employees);
		} catch (ManagerException e) {
			PlanimodPolicy.showException(e);
		}
	}
}
