/**
 * 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.admin.position;

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

import org.eclipse.core.databinding.BindingProperties;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.beans.IBeanValueProperty;
import org.eclipse.core.databinding.conversion.Converter;
import org.eclipse.core.databinding.conversion.IConverter;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.core.databinding.property.value.IValueProperty;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.databinding.util.JFaceProperties;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.databinding.viewers.ViewerProperties;
import org.eclipse.jface.databinding.viewers.ViewerSupport;
import org.eclipse.jface.viewers.ComboBoxViewerCellEditor;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;

import com.patrikdufresne.jface.databinding.viewers.ColumnSupport;
import com.patrikdufresne.jface.databinding.viewers.PropertyViewerComparator;
import com.patrikdufresne.jface.viewers.ColumnViewerPreferences;
import com.patrikdufresne.managers.databinding.ManagerUpdateValueStrategy;
import com.patrikdufresne.managers.jface.RemoveAction;
import com.planimod.core.AbstractCalendarEvent;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Position;
import com.planimod.core.Section;
import com.planimod.core.comparators.SectionComparators;
import com.planimod.ui.databinding.Converters;
import com.planimod.ui.databinding.ListObservableValue;
import com.planimod.ui.databinding.manager.PlanimodObservables;
import com.planimod.ui.preference.PlanimodPreferences;
import com.planimod.ui.views.AbstractViewPart;

/**
 * View to display and edit the position and it's related.
 * 
 * @author Patrik Dufresne
 * 
 */
public class PositionPageViewPart extends AbstractViewPart {
    /**
     * Localized string to identify classified position.
     */
    static final String CLASSIFIED = _("Attitré");
    /**
     * Converter used to filter the content of the view.
     */
    private static final IConverter CONVERTER = new Converter(Position.class, String.class) {

        @Override
        public Object convert(Object fromObject) {
            Position position = (Position) fromObject;
            StringBuilder buf = new StringBuilder();
            buf.append(position.getRefId());
            buf.append(SPACE);
            buf.append(position.getName());
            buf.append(SPACE);
            buf.append(position.getSection().getName());
            buf.append(SPACE);
            buf.append(position.getClassified() ? CLASSIFIED : EMPTY);
            return buf.toString();
        }

    };

    private static final String DOT = ".";

    /**
     * Empty string.
     */
    static final String EMPTY = "";

    /**
     * The part id.
     */
    public static final String ID = "com.planimod.ui.views.admin.position.PositionPageViewPart";
    /**
     * Preference key to access the column's width.
     */
    private static final String PREFERENCE_COLUMNS = "PositionViewPart.columns";

    /**
     * Space string.
     */
    static final String SPACE = " ";

    private RemoveAction removeAction;

    /**
     * The table viewer.
     */
    private TableViewer viewer;

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

    /**
     * This implementation create toolbar actions.
     */
    @Override
    public void activate(Composite parent) {

        // Create the table viewer.
        this.viewer = createTableViewer(parent);
        this.viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        this.viewer.getTable().setLinesVisible(PlanimodPreferences.getPreferenceStore().getBoolean(PlanimodPreferences.SHOW_LINES));

        // Populate the tool bar.
        fillToolBar();

        // Create binding
        bind();

    }

    /**
     * Bind the viewer and actions.
     */
    @Override
    protected void bindValues() {

        /*
         * Bind viewer
         */
        IObservableSet positions = PlanimodObservables.listPosition(getSite().getService(PlanimodManagers.class));
        this.viewer.setContentProvider(new ObservableSetContentProvider());
        createColumns(this.viewer, positions);
        this.viewer.setInput(filter(positions, CONVERTER));

        /*
         * Bind remove action
         */
        IObservableList selections = ViewerProperties.multipleSelection().observe(this.viewer);
        getDbc()
                .bindValue(
                        JFaceProperties.value(RemoveAction.class, RemoveAction.OBJECTS, RemoveAction.OBJECTS).observe(this.removeAction),
                        new ListObservableValue(selections, AbstractCalendarEvent.class));

    }

    /**
     * Create the column in the table viewer.
     * 
     * @param viewerthe
     *            table viewer
     * @param knownPositions
     *            the known position elements.
     */
    protected void createColumns(TableViewer viewer, IObservableSet knownPositions) {
        // RefId
        IBeanValueProperty redIfProperty = BeanProperties.value(Position.class, Position.REFID, String.class);
        ColumnSupport
                .create(viewer, _("No."), knownPositions, redIfProperty)
                .setWidth(75)
                .addPropertySorting()
                .addTextEditingSupport(
                        getDbc(),
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);

        // Name
        IBeanValueProperty nameProperty = BeanProperties.value(Position.class, Position.NAME, String.class);
        ColumnSupport
                .create(viewer, _("Nom"), knownPositions, nameProperty)
                .setWidth(150)
                .addPropertySorting()
                .addTextEditingSupport(
                        getDbc(),
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);

        // Section
        IObservableSet proposedSections = PlanimodObservables.listSection(getSite().getService(PlanimodManagers.class));
        IValueProperty proposedSectionLabel = BeanProperties
                .value(Section.class, Section.NAME)
                .value(BindingProperties.convertedValue(Converters.removeFrontNumber()));
        ComboBoxViewerCellEditor comboBoxCellEditor = new ComboBoxViewerCellEditor(viewer.getTable(), SWT.READ_ONLY);
        ComboViewer comboViewer = comboBoxCellEditor.getViewer();
        comboViewer.setComparator(new PropertyViewerComparator(SectionComparators.byName()));
        ViewerSupport.bind(comboViewer, proposedSections, proposedSectionLabel);

        IValueProperty sectionProperty = BeanProperties.value(Position.class, Position.SECTION, Section.class);
        IValueProperty sectionLabel = BeanProperties
                .value(Position.class, Position.SECTION + DOT + Section.NAME)
                .value(BindingProperties.convertedValue(Converters.removeFrontNumber()));
        ColumnSupport
                .create(viewer, _("Section"), knownPositions, sectionLabel)
                .setWidth(150)
                .addPropertySorting(sectionProperty, SectionComparators.byName())
                .activateSorting()
                .addViewerEditingSupport(
                        getDbc(),
                        sectionProperty,
                        comboBoxCellEditor,
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);

        // Classified
        IValueProperty classifiedProperty = BeanProperties.value(Position.class, Position.CLASSIFIED, Boolean.TYPE);
        IValueProperty classifiedLabel = classifiedProperty.value(BindingProperties.convertedValue(Converters.booleanConverter()));
        ColumnSupport
                .create(viewer, _("Attitré"), knownPositions, classifiedLabel)
                .setToolTipText(_("Cocher si le poste peut être attitré à un employé."))
                .addPropertySorting()
                .addCheckboxEditingSupport(
                        getDbc(),
                        classifiedProperty,
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);

        // Swappable
        IBeanValueProperty swappableProperty = BeanProperties.value(Position.class, Position.SWAPPABLE, Boolean.TYPE);
        IValueProperty swappablesLabel = swappableProperty.value(BindingProperties.convertedValue(Converters.booleanConverter()));
        ColumnSupport
                .create(viewer, _("Permutable"), knownPositions, swappablesLabel)
                .addPropertySorting()
                .addCheckboxEditingSupport(
                        getDbc(),
                        swappableProperty,
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);

        ColumnViewerPreferences.create(viewer, PlanimodPreferences.getPreferenceStore(), PREFERENCE_COLUMNS);
    }

    @Override
    public void deactivate() {
        this.removeAction = null;
        this.viewer = null;
        super.deactivate();
    }

    @Override
    public void dispose() {
        super.dispose();
    }

    /**
     * Populate the tool bar.
     */
    void fillToolBar() {

        IToolBarManager toolbar = getSite().getToolBarManager();

        // Add
        ActionContributionItem aci;
        toolbar.add(aci = new ActionContributionItem(new AddPositionAction(getSite().getService(PlanimodManagers.class), getSite(), this.viewer)));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);

        // Remove
        toolbar.add(aci = new ActionContributionItem(this.removeAction = new RemoveAction(getSite().getService(PlanimodManagers.class), getSite())));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);

        // Text filter
        fillToolbarWithTextFilter();
    }

}
