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

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

import org.eclipse.core.databinding.DataBindingContext;
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.map.IObservableMap;
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.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.databinding.util.JFaceProperties;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.databinding.viewers.ViewerProperties;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.patrikdufresne.jface.databinding.viewers.ColumnSupport;
import com.patrikdufresne.jface.databinding.viewers.TextProposalViewerUpdater;
import com.patrikdufresne.jface.viewers.ColumnViewerPreferences;
import com.patrikdufresne.jface.viewers.TextProposalViewerCellEditor;
import com.patrikdufresne.managers.databinding.ManagerUpdateValueStrategy;
import com.patrikdufresne.managers.jface.RemoveAction;
import com.patrikdufresne.printing.PrintAction;
import com.patrikdufresne.ui.SashFactory;
import com.planimod.core.AbstractCalendarEvent;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Position;
import com.planimod.core.Product;
import com.planimod.core.ProductPosition;
import com.planimod.ui.databinding.ListObservableValue;
import com.planimod.ui.databinding.manager.PlanimodObservables;
import com.planimod.ui.preference.PlanimodPreferences;
import com.planimod.ui.printing.PrintActionMenuManager;
import com.planimod.ui.views.AbstractViewPart;

/**
 * View to edit the products.
 * 
 * @author Patrik Dufresne
 */
public class ProductPageViewPart extends AbstractViewPart {

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

        @Override
        public Object convert(Object fromObject) {
            Product product = (Product) fromObject;
            StringBuilder buf = new StringBuilder();
            buf.append(product.getRefId());
            buf.append(SPACE);
            buf.append(product.getName());
            buf.append(SPACE);
            buf.append(product.getFamily());
            return buf.toString();
        }
    };

    private static final String DOT = ".";

    /**
     * The part id.
     */
    public static final String ID = "com.planimod.ui.views.admin.product.ProductPageViewPart";

    /**
     * Preference key to access the column's width.
     */
    private static final String PREFERENCE_COLUMNS = "ProductViewPart.columns";

    /**
     * Preference key to access the column's width.
     */
    private static final String PREFERENCE_EDITOR_COLUMNS = "ProductEditor.columns";

    /**
     * Default sash weights.
     */
    private static final int PREFERENCE_SASH_DEFAULT_WIDTH = 320;

    private static final String PREFERENCE_SASH_WIDTH = "ProductViewPart.sash.width";

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

    private AddProductPositionAction addActionProductPosition;

    private DuplicateProductAction duplicateProductAction;

    private Text familyText;

    /**
     * Used to edit the product's name.
     */
    private Text nameText;

    /**
     * Viewer to display the associated position.
     */
    private TableViewer productPositionViewer;

    /**
     * Used to edit the employee's lastname.
     */
    private Text refIdText;

    private RemoveAction removeAction;

    private RemoveAction removeActionProductPosition;

    private TableViewer viewer;

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

    /**
     * This implementation create the content of the product view.
     */
    @Override
    public void activate(Composite parent) {
        // Create the viewer on the left.
        this.viewer = createTableViewer(parent);
        this.viewer.getTable().setLinesVisible(PlanimodPreferences.getPreferenceStore().getBoolean(PlanimodPreferences.SHOW_LINES));
        // Create the editor on the right.
        createEditorControls(parent);
        // Create the sash
        SashFactory.createRightPane(parent, false, PlanimodPreferences.getPreferenceStore(), PREFERENCE_SASH_WIDTH, PREFERENCE_SASH_DEFAULT_WIDTH);
        // Populate the tool bar.
        fillToolBar();
        // Create binding
        bind();
    }

    /**
     * Bind the viewer and the editor.
     */
    @Override
    protected void bindValues() {
        DataBindingContext dbc = getDbc();
        PlanimodManagers managers = getSite().getService(PlanimodManagers.class);
        /*
         * Bind viewer
         */
        IObservableSet products = PlanimodObservables.listProduct(managers);
        this.viewer.setContentProvider(new ObservableSetContentProvider());
        createColumns(this.viewer, products);
        this.viewer.setInput(filter(products, CONVERTER));
        /*
         * Bind editor
         */
        IObservableValue selectedProduct = ViewerProperties.singleSelection().observe(this.viewer);
        // RefId
        IObservableValue refId = BeanProperties.value(Product.class, Product.REFID, String.class).observeDetail(selectedProduct);
        dbc.bindValue(WidgetProperties.text(SWT.FocusOut).observe(this.refIdText), refId, new ManagerUpdateValueStrategy(managers), null);
        // Name
        IObservableValue name = BeanProperties.value(Product.class, Product.NAME, String.class).observeDetail(selectedProduct);
        dbc.bindValue(WidgetProperties.text(SWT.FocusOut).observe(this.nameText), name, new ManagerUpdateValueStrategy(managers), null);
        // Family
        IObservableValue family = BeanProperties.value(Product.class, Product.FAMILY, String.class).observeDetail(selectedProduct);
        dbc.bindValue(WidgetProperties.text(SWT.FocusOut).observe(this.familyText), family, new ManagerUpdateValueStrategy(managers), null);
        /*
         * Bind position viewer
         */
        IObservableSet productPositions = new ProductPositionByProductComputedSet(managers, selectedProduct);
        this.productPositionViewer.setContentProvider(new ObservableSetContentProvider());
        createProductPositionColumns(this.productPositionViewer, productPositions);
        this.productPositionViewer.setInput(productPositions);
        // Bind editor actions
        dbc
                .bindValue(
                        JFaceProperties
                                .value(AddProductPositionAction.class, AddProductPositionAction.PRODUCT, AddProductPositionAction.PRODUCT)
                                .observe(this.addActionProductPosition),
                        selectedProduct);
        dbc
                .bindValue(
                        JFaceProperties.value(RemoveAction.class, RemoveAction.OBJECT, RemoveAction.OBJECT).observe(this.removeActionProductPosition),
                        ViewerProperties.singleSelection().observe(this.productPositionViewer));
        /*
         * Bind 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));
        dbc
                .bindValue(
                        JFaceProperties
                                .value(DuplicateProductAction.class, DuplicateProductAction.PRODUCT, DuplicateProductAction.PRODUCT)
                                .observe(this.duplicateProductAction),
                        selectedProduct);

    }

    /**
     * Create the columns in the table viewer.
     * 
     * @param viewerthe
     *            table viewer
     * @param knownProducts
     *            the known product elements
     */
    protected void createColumns(TableViewer viewer, IObservableSet knownProducts) {
        // RefId
        IBeanValueProperty refIdProperty = BeanProperties.value(Product.class, Product.REFID);
        ColumnSupport
                .create(viewer, _("No."), knownProducts, refIdProperty)
                .setWidth(75)
                .addPropertySorting()
                .addTextEditingSupport(
                        getDbc(),
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);
        // Name
        IBeanValueProperty nameProperty = BeanProperties.value(Product.class, Product.NAME);
        ColumnSupport
                .create(viewer, _("Nom"), knownProducts, nameProperty)
                .setWidth(250)
                .addPropertySorting()
                .addTextEditingSupport(
                        getDbc(),
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);
        // Family
        IBeanValueProperty familyProperty = BeanProperties.value(Product.class, Product.FAMILY);
        ColumnSupport
                .create(viewer, _("Famille"), knownProducts, familyProperty)
                .setWidth(150)
                .addPropertySorting()
                .addTextEditingSupport(
                        getDbc(),
                        new ManagerUpdateValueStrategy(getSite().getService(PlanimodManagers.class), UpdateValueStrategy.POLICY_CONVERT),
                        null);
        ColumnViewerPreferences.create(viewer, PlanimodPreferences.getPreferenceStore(), PREFERENCE_COLUMNS);
    }

    private void createEditorControls(Composite parent) {
        Composite comp = new Composite(parent, SWT.NONE);
        comp.setLayout(new GridLayout(2, false));
        /*
         * RefId
         */
        Label label = new Label(comp, SWT.NONE);
        label.setText(_("No. :"));
        this.refIdText = new Text(comp, SWT.BORDER);
        this.refIdText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        /*
         * Name
         */
        label = new Label(comp, SWT.NONE);
        label.setText(_("Nom :"));
        this.nameText = new Text(comp, SWT.BORDER);
        this.nameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        /*
         * Family
         */
        label = new Label(comp, SWT.NONE);
        label.setText(_("Famille :"));
        this.familyText = new Text(comp, SWT.BORDER);
        this.familyText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
        /*
         * Associated position
         */
        label = new Label(comp, SWT.NONE);
        label.setText(_("Liste des postes requise:"));
        label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
        Composite comp2 = new Composite(comp, SWT.NONE);
        this.productPositionViewer = createTableViewer(comp2);
        comp2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 50));
        /*
         * Buttons to alter the list
         */
        GridLayout buttonLayout = new GridLayout(2, false);
        buttonLayout.marginHeight = 0;
        buttonLayout.marginWidth = 0;
        Composite buttonComp = new Composite(comp, SWT.NONE);
        buttonComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
        buttonComp.setLayout(buttonLayout);
        // Add action
        ActionContributionItem aci;
        aci = new ActionContributionItem(
                this.addActionProductPosition = new AddProductPositionAction(
                        getSite().getService(PlanimodManagers.class),
                        getSite(),
                        this.productPositionViewer));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        aci.fill(buttonComp);
        ((Button) aci.getWidget()).setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
        // Remove action
        aci = new ActionContributionItem(this.removeActionProductPosition = new RemoveAction(getSite().getService(PlanimodManagers.class), getSite()));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        aci.fill(buttonComp);
        ((Button) aci.getWidget()).setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
        /*
         * Spacer
         */
        label = new Label(comp, SWT.NONE);
        label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
    }

    /**
     * Create the required columns to display end edit the product-position.
     * 
     * @param viewer
     */
    private void createProductPositionColumns(final TableViewer viewer, IObservableSet knownElements) {
        DataBindingContext dbc = getDbc();
        PlanimodManagers managers = getSite().getService(PlanimodManagers.class);
        // Number
        final IValueProperty numberProperty = BeanProperties.value(ProductPosition.class, ProductPosition.NUMBER, Integer.class);
        ColumnSupport
                .create(viewer, _("Nombre"), knownElements, numberProperty)
                .addPropertySorting()
                .addTextEditingSupport(dbc, new ManagerUpdateValueStrategy(managers, UpdateValueStrategy.POLICY_CONVERT), null)
                .setPixelLayoutData(25)
                .setMoveable(false);
        // Position
        IObservableSet positionProposeds = PlanimodObservables.listPosition(managers);
        IObservableMap positionProposedLabels = BeanProperties.value(Position.class, Position.NAME).observeDetail(positionProposeds);
        final TextProposalViewerCellEditor proposalCellEditor = new TextProposalViewerCellEditor(viewer.getTable());
        proposalCellEditor.setContentProvider(new ObservableSetContentProvider(new TextProposalViewerUpdater(proposalCellEditor.getViewer())));
        proposalCellEditor.setLabelProvider(new ObservableMapLabelProvider(positionProposedLabels));
        proposalCellEditor.setInput(positionProposeds);
        IValueProperty positionProperty = BeanProperties.value(ProductPosition.class, ProductPosition.POSITION, Position.class);
        IValueProperty positionLabel = BeanProperties.value(ProductPosition.class, ProductPosition.POSITION + DOT + Position.NAME, Position.class);
        ColumnSupport
                .create(viewer, _("Poste"), knownElements, positionLabel)
                .setWidth(150)
                .addViewerEditingSupport(
                        dbc,
                        positionProperty,
                        proposalCellEditor,
                        new ManagerUpdateValueStrategy(managers, UpdateValueStrategy.POLICY_CONVERT),
                        null)
                .setWeightLayoutData(1, 75)
                .setResizable(false)
                .setMoveable(false);
        ColumnViewerPreferences.create(viewer, PlanimodPreferences.getPreferenceStore(), PREFERENCE_EDITOR_COLUMNS);
    }

    @Override
    public void deactivate() {
        try {
            this.addActionProductPosition = null;
            this.familyText = null;
            this.nameText = null;
            this.productPositionViewer = null;
            this.refIdText = null;
            this.removeAction = null;
            this.viewer = null;
        } finally {
            super.deactivate();
        }
    }

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

    /**
     * Populate the tool bar.
     */
    void fillToolBar() {
        /*
         * Add action to tool-bar
         */
        IToolBarManager toolbar = getSite().getToolBarManager();
        PlanimodManagers managers = getSite().getService(PlanimodManagers.class);
        // Add
        ActionContributionItem aci;
        toolbar.add(aci = new ActionContributionItem(new AddProductAction(managers, getSite(), this.viewer)));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        // Remove
        toolbar.add(aci = new ActionContributionItem(this.removeAction = new RemoveAction(managers, getSite())));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        // Duplicate
        toolbar.add(aci = new ActionContributionItem(this.duplicateProductAction = new DuplicateProductAction(managers, getSite(), this.viewer)));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        // Separator
        toolbar.add(new Separator());
        /*
         * Add Print actions
         */
        PrintActionMenuManager printMenu = new PrintActionMenuManager("ProductPageViewPart.printMenu");
        printMenu.add(new ProductPositionPrintAction(managers, getSite(), PrintAction.PRINT_ACTION, getSite().getMainWindow()));
        printMenu.add(new ProductPositionPrintAction(managers, getSite(), PrintAction.PREVIEW_ACTION, getSite().getMainWindow()));
        toolbar.add(printMenu);
        // Text filter
        fillToolbarWithTextFilter();
    }
}
