/*
 * Copyright (c) 2011, Patrik Dufresne. All rights reserved. Patrik Dufresne
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.planimod.ui.views.qualifs;

import org.eclipse.core.databinding.BindingProperties;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.conversion.Converter;
import org.eclipse.core.databinding.conversion.IConverter;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.property.value.IValueProperty;
import org.eclipse.core.internal.databinding.property.value.SelfValueProperty;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.databinding.viewers.ViewersObservables;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import com.patrikdufresne.jface.databinding.viewers.ColumnSupport;
import com.patrikdufresne.jface.viewers.ColumnViewerPreferences;
import com.patrikdufresne.printing.PrintAction;
import com.patrikdufresne.ui.SashFactory;
import com.patrikdufresne.util.Localized;
import com.planimod.core.Employee;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Position;
import com.planimod.core.Section;
import com.planimod.core.comparators.EmployeeComparators;
import com.planimod.core.comparators.SectionComparators;
import com.planimod.ui.databinding.Converters;
import com.planimod.ui.databinding.SetContainsPropertyValue;
import com.planimod.ui.databinding.manager.PlanimodObservables;
import com.planimod.ui.preference.PlanimodPreferences;
import com.planimod.ui.printing.PrintActionMenuManager;
import com.planimod.ui.viewers.EmployeeViewerUtils;
import com.planimod.ui.views.AbstractViewPart;

/**
 * @author Patrik Dufresne
 */
public class QualificationViewPart extends AbstractViewPart {

    private static final IConverter CONVERTER = new Converter(Position.class,
            String.class) {

        @Override
        public Object convert(Object fromObject) {
            return ((Position) fromObject).getName() + " " //$NON-NLS-1$
                    + ((Position) fromObject).getRefId() + " " //$NON-NLS-1$
                    + ((Position) fromObject).getSection().getName();
        }
    };

    private static final String DOT = "."; //$NON-NLS-1$

    /**
     * The part id.
     */
    public static final String ID =
            "com.planimod.ui.views.qualifs.QualificationViewPart"; //$NON-NLS-1$

    /**
     * Key used to store the columns preferences.
     */
    private static final String PREFERENCE_EMPLOYEE_COLUMNS =
            "QualificationViewPart.employee..columns"; //$NON-NLS-1$

    private static final String PREFERENCE_POSITION_COLUMNS =
            "QualificationViewPart.position.columns"; //$NON-NLS-1$

    /**
     * Key used to store the sash weight.
     */
    private static final String PREFERENCE_SASH_WIDTH =
            "QualificationViewPart.sash.width"; //$NON-NLS-1$

    /**
     * The default pane width.
     */
    private static final int PREFERENCES_SASH_WIDTH_DEFAULT = 320;

    /**
     * Left sided employee viewer
     */
    private TableViewer employeeViewer;

    /**
     * Used for localization.
     */
    private Localized localized = Localized.load(QualificationViewPart.class);

    private TableViewer positionViewer;

    /**
     * Create a new view part.
     */
    public QualificationViewPart() {
        super(ID);
        setTitle(this.localized.get("QualificationViewPart.title")); //$NON-NLS-1$
    }

    /**
     * This implementation add a table viewer to the left.
     */
    @Override
    public void activate(Composite parent) {
        /*
         * Create table viewer on the left
         */
        this.employeeViewer = createTableViewer(parent, SWT.SINGLE);
        /*
         * Create table viewer on the right
         */
        this.positionViewer = createTableViewer(parent);
        this.positionViewer.getTable().setLinesVisible(
                PlanimodPreferences.getPreferenceStore().getBoolean(
                        PlanimodPreferences.SHOW_LINES));
        // Create the sash
        SashFactory.createLeftPane(parent, false,
                PlanimodPreferences.getPreferenceStore(), PREFERENCE_SASH_WIDTH,
                PREFERENCES_SASH_WIDTH_DEFAULT);
        // Populate the tool bar.
        fillToolBar();
        // Create binding
        bind();
    }

    /**
     * This function is used to bind the UI to the model
     */
    @Override
    protected void bindValues() {
        /*
         * Configure the employee viewer
         */
        IObservableSet employees =
                PlanimodObservables.listEmployees(getSite().getService(
                        PlanimodManagers.class));
        createEmployeeColumns(this.employeeViewer, employees);
        this.employeeViewer.setContentProvider(new ObservableSetContentProvider());
        this.employeeViewer.setInput(employees);
        /*
         * Configure the main viewer
         */
        IObservableSet positions =
                PlanimodObservables.listPosition(getSite().getService(
                        PlanimodManagers.class));
        createPositionColumns(this.positionViewer, positions);
        this.positionViewer.setContentProvider(new ObservableSetContentProvider());
        this.positionViewer.setInput(filter(positions, CONVERTER));
    }

    /**
     * Create the columns for the employee viewer.
     * 
     * @param viewer the table viewer
     * @param knownEmployees the known employee elements
     */
    protected void createEmployeeColumns(TableViewer viewer,
            IObservableSet knownEmployees) {
        // Employee
        ColumnSupport
                .create(viewer,
                        this.localized.get("QualificationViewPart.column.employee"), //$NON-NLS-1$
                        knownEmployees,
                        BindingProperties.convertedValue(EmployeeViewerUtils
                                .fullnameConverter()))
                .setWidth(150)
                .addPropertySorting(new SelfValueProperty(Employee.class),
                        EmployeeComparators.byName()).activateSorting();
        // HireDate
        ColumnSupport.create(
                viewer,
                this.localized.get("QualificationViewPart.column.hireDate"), //$NON-NLS-1$
                knownEmployees,
                BeanProperties.value(Employee.class, Employee.HIRE_DATE).value(
                        BindingProperties.convertedValue(Converters
                                .shortDateConverter()))).addPropertySorting(
                new SelfValueProperty(Employee.class),
                EmployeeComparators.bySeniority());
        ColumnViewerPreferences.create(viewer,
                PlanimodPreferences.getPreferenceStore(), PREFERENCE_EMPLOYEE_COLUMNS);
    }

    /**
     * Create the columns for the default viewer.
     * 
     * @param viewer
     * @param positions
     */
    protected void createPositionColumns(TableViewer viewer,
            IObservableSet knownElements) {
        // Section name
        IValueProperty sectionProperty =
                BeanProperties.value(Position.class, Position.SECTION);
        IValueProperty sectionLabel =
                BeanProperties.value(Position.class,
                        Position.SECTION + DOT + Section.NAME).value(
                        BindingProperties.convertedValue(Converters
                                .removeFrontNumber()));
        ColumnSupport
                .create(viewer,
                        this.localized.get("QualificationViewPart.column.section"), //$NON-NLS-1$
                        knownElements, sectionLabel).setWidth(150)
                .addPropertySorting(sectionProperty, SectionComparators.byName())
                .activateSorting();
        // Position name
        IValueProperty positionLabel =
                BeanProperties.value(Position.class, Position.NAME);
        ColumnSupport.create(viewer,
                this.localized.get("QualificationViewPart.column.position"), //$NON-NLS-1$
                knownElements, positionLabel).addPropertySorting();
        // Qualify
        IObservableValue selectedEmployee =
                ViewersObservables.observeSingleSelection(this.employeeViewer);
        IObservableSet qualifiedPosition =
                new QualifyPositionComputedSet(getSite().getService(
                        PlanimodManagers.class), selectedEmployee);
        IValueProperty employeeIsQualify =
                new SetContainsPropertyValue(qualifiedPosition);
        IValueProperty employeeIsQualifyLabel =
                employeeIsQualify.value(BindingProperties.convertedValue(Converters
                        .booleanConverter()));
        ColumnSupport
                .create(viewer,
                        this.localized.get("QualificationViewPart.column.qualify"), //$NON-NLS-1$
                        knownElements, employeeIsQualifyLabel).addPropertySorting()
                .addCheckboxEditingSupport(getDbc(), employeeIsQualify);
        // Attach a columns preferences
        ColumnViewerPreferences.create(viewer,
                PlanimodPreferences.getPreferenceStore(), PREFERENCE_POSITION_COLUMNS);
    }

    /**
     * This implementation free allocated resources.
     */
    @Override
    public void deactivate() {
        this.employeeViewer = null;
        this.positionViewer = null;
        super.deactivate();
    }

    @Override
    public void dispose() {
        this.localized = null;
        super.dispose();
    }

    /**
     * Populate the view site tool bar.
     */
    void fillToolBar() {
        IToolBarManager toolbar = getSite().getToolBarManager();
        toolbar.removeAll();
        // Print menu
        PrintActionMenuManager printMenu =
                new PrintActionMenuManager("QualificationViewPart.printMenu"); //$NON-NLS-1$
        printMenu.add(new QualificationPrintAction(getSite().getService(
                PlanimodManagers.class), getSite(), PrintAction.PRINT_ACTION,
                getSite().getMainWindow()));
        printMenu.add(new QualificationPrintAction(getSite().getService(
                PlanimodManagers.class), getSite(), PrintAction.PREVIEW_ACTION,
                getSite().getMainWindow()));
        toolbar.add(printMenu);
        // Filter
        fillToolbarWithTextFilter();
    }
}
