/**
 * Copyright (C) 2019 Patrik Dufresne Service Logiciel <info@patrikdufresne.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package com.planimod.ui.views.qualifs;

import static com.planimod.ui.Localized._;

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.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() + " " + ((Position) fromObject).getRefId() + " " + ((Position) fromObject).getSection().getName();
        }
    };

    private static final String DOT = ".";

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

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

    private static final String PREFERENCE_POSITION_COLUMNS = "QualificationViewPart.position.columns";

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

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

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

    private TableViewer positionViewer;

    /**
     * Create a new view part.
     */
    public QualificationViewPart() {
        super(ID);
        setTitle(_("Formations"));
    }

    /**
     * This implementation add a table viewer to the left.
     */
    @Override
    public void activate(Composite parent) {
        /*
         * Create table viewer on the left
         */
        Composite comp = new Composite(parent, SWT.NONE);
        this.employeeViewer = createTableViewer(comp);
        /*
         * 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, _("Employé"), knownEmployees, BindingProperties.convertedValue(EmployeeViewerUtils.fullnameConverter()))
                .addPropertySorting(new SelfValueProperty(Employee.class), EmployeeComparators.byName())
                .activateSorting()
                .setWeightLayoutData(2, 75)
                .setMoveable(false);
        // HireDate
        ColumnSupport
                .create(
                        viewer,
                        _("Date d'embauche"),
                        knownEmployees,
                        BeanProperties.value(Employee.class, Employee.HIRE_DATE).value(BindingProperties.convertedValue(Converters.shortDateConverter())))
                .addPropertySorting(new SelfValueProperty(Employee.class), EmployeeComparators.bySeniority())
                .setWeightLayoutData(1, 75)
                .setMoveable(false)
                .setResizable(false);
    }

    /**
     * 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, _("Section"), knownElements, sectionLabel)
                .setWidth(150)
                .addPropertySorting(sectionProperty, SectionComparators.byName())
                .activateSorting();
        // Position name
        IValueProperty positionLabel = BeanProperties.value(Position.class, Position.NAME);
        ColumnSupport.create(viewer, _("Poste"), knownElements, positionLabel).addPropertySorting().setWidth(300);
        // 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, _("Formé"), 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() {
        super.dispose();
    }

    /**
     * Populate the view site tool bar.
     */
    void fillToolBar() {
        IToolBarManager toolbar = getSite().getToolBarManager();
        toolbar.removeAll();
        // Print menu
        PrintActionMenuManager printMenu = new PrintActionMenuManager("QualificationViewPart.printMenu");
        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();
    }
}
