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

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

import java.beans.PropertyDescriptor;
import java.util.Date;

import org.eclipse.core.databinding.BindingProperties;
import org.eclipse.core.databinding.UpdateListStrategy;
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.list.WritableList;
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.observable.value.WritableValue;
import org.eclipse.core.databinding.property.value.IValueProperty;
import org.eclipse.core.internal.databinding.beans.BeanPropertyHelper;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.databinding.util.JFaceProperties;
import org.eclipse.jface.databinding.viewers.ObservableSetContentProvider;
import org.eclipse.jface.databinding.viewers.ViewersObservables;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.OpenEvent;
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.preference.PreferenceStoreProperties;
import com.patrikdufresne.jface.databinding.viewers.ColumnSupport;
import com.patrikdufresne.jface.databinding.viewers.PropertyViewerComparator;
import com.patrikdufresne.jface.viewers.ColumnViewerPreferences;
import com.patrikdufresne.managers.jface.RemoveAction;
import com.patrikdufresne.planner.Planner;
import com.patrikdufresne.planner.databinding.ObservableMapPlannerLabelProvider;
import com.patrikdufresne.planner.databinding.PlannerProperties;
import com.patrikdufresne.planner.databinding.PlannerViewerUpdater;
import com.patrikdufresne.planner.viewer.PlannerViewer;
import com.patrikdufresne.printing.PrintAction;
import com.planimod.core.AbstractCalendarEvent;
import com.planimod.core.NonAvailability;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.comparators.NonAvailabilityComparators;
import com.planimod.ui.databinding.BeanComputedValueProperty;
import com.planimod.ui.databinding.ComputedObservableTimeRange;
import com.planimod.ui.databinding.DateColorControlStyleSupport;
import com.planimod.ui.databinding.DateFormatRangeValueProperty;
import com.planimod.ui.databinding.ListObservableValue;
import com.planimod.ui.preference.PlanimodPreferences;
import com.planimod.ui.printing.PrintActionMenuManager;
import com.planimod.ui.viewers.EmployeeViewerUtils;
import com.planimod.ui.viewers.planner.PlanimodPlannerLook;
import com.planimod.ui.views.AbstractViewPart;
import com.planimod.ui.views.ChangeDateAction;

/**
 * This view part display employee's non-availabilities.
 * 
 * @author Patrik Dufresne
 */
public class NonAvailabilitiesViewPart extends AbstractViewPart {

    /**
     * The part id.
     */
    public static final String ID = "NonAvailabilitiesViewPart";

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

    /**
     * Key used to store the sash weight.
     */
    private static final String PREFERENCE_SASH_WEIGHTS = "NonAvailabilitiesViewPart.sash.weights";

    /**
     * Default sash weights.
     */
    private static final int[] PREFERENCE_SASH_DEFAULT_WEIGHTS = new int[] { 70, 30 };

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

        @Override
        public Object convert(Object fromObject) {
            NonAvailability na = (NonAvailability) fromObject;
            StringBuilder buf = new StringBuilder();
            buf.append(na.getSummary());
            buf.append(" ");
            buf.append(na.getEmployee().getFirstname());
            buf.append(" ");
            buf.append(na.getEmployee().getLastname());
            return buf.toString();
        }
    };

    private AddNonAvailabilityAction addNonAvailability;

    /**
     * Action used to edit a non-availability event.
     */
    EditNonAvailabilityAction editNonAvailability;

    private TableViewer longEventViewer;

    /**
     * Next action.
     */
    private ChangeDateAction nextAction;

    /**
     * Preview action.
     */
    private NonAvailabilityPrintAction previewAllAction;

    /**
     * Previous action.
     */
    private ChangeDateAction previousAction;

    /**
     * Printing action.
     */
    private NonAvailabilityPrintAction printAllAction;

    /**
     * Remove action.
     */
    private RemoveAction removeAction;

    /**
     * Today action.
     */
    private ChangeDateAction todayAction;

    private PlannerViewer viewer;

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

    /**
     * This implementation create the tool-bar action.
     */
    @Override
    public void activate(Composite parent) {
        SashForm sash = createSashForm(
                parent,
                SWT.HORIZONTAL | SWT.SMOOTH,
                PlanimodPreferences.getPreferenceStore(),
                PREFERENCE_SASH_WEIGHTS,
                PREFERENCE_SASH_DEFAULT_WEIGHTS);
        sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        /*
         * Create planner viewer on the left
         */
        this.viewer = createPlannerViewer(sash);
        /*
         * Create table viewer on the right.
         */
        this.longEventViewer = createTableViewer(sash);
        this.longEventViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        this.longEventViewer.getTable().setHeaderVisible(true);
        // A open listener to edit the event
        this.longEventViewer.addOpenListener(new IOpenListener() {

            @Override
            public void open(OpenEvent event) {
                // JFace data binding, this action is already updated with the
                // current selection. We only need to run the action.
                NonAvailabilitiesViewPart.this.editNonAvailability.run();
            }
        });
        // Populate the tool bar.
        fillToolBar();
        // Create binding
        bind();
    }

    /**
     * Binds the planner date selection to a shared state.
     */
    @Override
    protected void bindValues() {
        /*
         * Bind current selection to intermediate variable since there is two selection provider.
         */
        IObservableValue singleSelection = new WritableValue();
        getDbc()
                .bindValue(
                        ViewersObservables.observeSingleSelection(this.viewer),
                        singleSelection,
                        null,
                        new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER));
        getDbc()
                .bindValue(
                        ViewersObservables.observeSingleSelection(this.longEventViewer),
                        singleSelection,
                        null,
                        new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER));
        IObservableList selection = new WritableList();
        getDbc().bindList(ViewersObservables.observeMultiSelection(this.viewer), selection, null, new UpdateListStrategy(UpdateListStrategy.POLICY_NEVER));
        getDbc()
                .bindList(
                        ViewersObservables.observeMultiSelection(this.longEventViewer),
                        selection,
                        null,
                        new UpdateListStrategy(UpdateListStrategy.POLICY_NEVER));
        /*
         * Get the date state.
         */
        final WritableValue date = new WritableValue(null, Date.class);
        getDbc().bindValue(date, PreferenceStoreProperties.value(PlanimodPreferences.DATE, String.class).observe(PlanimodPreferences.getPreferenceStore()));
        if (date.getValue() == null) {
            date.setValue(new Date());
        }
        /*
         * Bind date with planner date selection.
         */
        Planner planner = (Planner) this.viewer.getControl();
        getDbc().bindValue(PlannerProperties.dateSelection().observe(planner), date);
        IObservableValue start = PlannerProperties.startDateValue().observe(planner);
        IObservableValue end = PlannerProperties.endDateValue().observe(planner);
        IObservableValue timeRange = new ComputedObservableTimeRange(start, end);
        /*
         * Bind the planner viewer (visible availabilities)
         */
        IObservableSet nonAvailabilities = filter(new NonAvailabilitiesComputedSet(getSite().getService(PlanimodManagers.class), timeRange, true), CONVERTER);
        ObservableSetContentProvider oscp = new ObservableSetContentProvider(new PlannerViewerUpdater(this.viewer));
        this.viewer.setContentProvider(oscp);
        this.viewer.setComparator(new PropertyViewerComparator(NonAvailabilityComparators.byDateAndEmployeeName()));
        this.viewer.setLabelProvider(createPlannerLabelProvider(oscp.getKnownElements()));
        this.viewer.setInput(nonAvailabilities);
        DateColorControlStyleSupport.create(this.viewer.getPlanner(), date);
        /*
         * Bind table viewer (hidden non-availabilities)
         */
        ObservableSetContentProvider oscp2 = new ObservableSetContentProvider();
        this.longEventViewer.setContentProvider(oscp2);
        createColumns(this.longEventViewer, oscp2.getKnownElements());
        this.longEventViewer.setInput(nonAvailabilities);
        /*
         * Bind actions
         */
        getDbc().bindValue(JFaceProperties.value(ChangeDateAction.class, ChangeDateAction.DATE, ChangeDateAction.DATE).observe(this.previousAction), date);
        getDbc().bindValue(JFaceProperties.value(ChangeDateAction.class, ChangeDateAction.DATE, ChangeDateAction.DATE).observe(this.todayAction), date);
        getDbc().bindValue(JFaceProperties.value(ChangeDateAction.class, ChangeDateAction.DATE, ChangeDateAction.DATE).observe(this.nextAction), date);
        getDbc()
                .bindValue(
                        JFaceProperties
                                .value(NonAvailabilityPrintAction.class, NonAvailabilityPrintAction.DATE, NonAvailabilityPrintAction.DATE)
                                .observe(this.printAllAction),
                        date);
        getDbc()
                .bindValue(
                        JFaceProperties
                                .value(NonAvailabilityPrintAction.class, NonAvailabilityPrintAction.DATE, NonAvailabilityPrintAction.DATE)
                                .observe(this.previewAllAction),
                        date);
        getDbc()
                .bindValue(
                        JFaceProperties
                                .value(AddNonAvailabilityAction.class, AddNonAvailabilityAction.DATE, AddNonAvailabilityAction.DATE)
                                .observe(this.addNonAvailability),
                        date);
        getDbc()
                .bindValue(
                        JFaceProperties
                                .value(EditNonAvailabilityAction.class, EditNonAvailabilityAction.NON_AVAILABILITY, EditNonAvailabilityAction.NON_AVAILABILITY)
                                .observe(this.editNonAvailability),
                        singleSelection);
        getDbc()
                .bindValue(
                        JFaceProperties.value(RemoveAction.class, RemoveAction.OBJECTS, RemoveAction.OBJECTS).observe(this.removeAction),
                        new ListObservableValue(selection, AbstractCalendarEvent.class));
    }

    /**
     * Create the label provider for the planner viewer.
     * 
     * @param knownElements
     *            the know elements
     * @return the label provider.
     */
    private IBaseLabelProvider createPlannerLabelProvider(IObservableSet knownElements) {
        // Create the property descriptor.
        PropertyDescriptor[] properties = new PropertyDescriptor[] {
                BeanPropertyHelper.getPropertyDescriptor(NonAvailability.class, NonAvailability.EMPLOYEE),
                BeanPropertyHelper.getPropertyDescriptor(NonAvailability.class, AbstractCalendarEvent.SUMMARY) };
        IObservableMap nonAvailabilityLabels = (new BeanComputedValueProperty(properties, String.class) {

            IConverter convert = EmployeeViewerUtils.fullnameConverter();

            @Override
            protected Object doGetValue(Object source) {
                NonAvailability na = (NonAvailability) source;
                StringBuilder buf = new StringBuilder();
                buf.append(convert.convert(na.getEmployee()));
                buf.append(" - ");
                buf.append(na.getSummary());
                return buf.toString();
            }
        }).observeDetail(knownElements);
        IObservableMap nonAvailabilityStart = BeanProperties.value(AbstractCalendarEvent.class, AbstractCalendarEvent.START_DATE).observeDetail(knownElements);
        IObservableMap nonAvailabilityEnd = BeanProperties.value(AbstractCalendarEvent.class, AbstractCalendarEvent.END_DATE).observeDetail(knownElements);
        return new ObservableMapPlannerLabelProvider(nonAvailabilityLabels, nonAvailabilityStart, nonAvailabilityEnd);
    }

    protected void createColumns(TableViewer viewer, IObservableSet knownElements) {
        // Employee's name
        IValueProperty employeeLabel = BeanProperties
                .value(NonAvailability.class, NonAvailability.EMPLOYEE)
                .value(BindingProperties.convertedValue(EmployeeViewerUtils.fullnameConverter()));
        ColumnSupport.create(viewer, _("Employé"), knownElements, employeeLabel).setWidth(150).addPropertySorting().activateSorting();
        // Date range
        IValueProperty dateRangeLabel = DateFormatRangeValueProperty.createDateShort();
        IBeanValueProperty startDateProperty = BeanProperties.value(AbstractCalendarEvent.class, AbstractCalendarEvent.START_DATE, Date.class);
        ColumnSupport.create(viewer, _("Absences"), knownElements, dateRangeLabel).setWidth(200).addPropertySorting(startDateProperty);
        // Summary
        IValueProperty summaryProperty = BeanProperties.value(AbstractCalendarEvent.class, AbstractCalendarEvent.SUMMARY);
        ColumnSupport.create(viewer, _("Motif"), knownElements, summaryProperty).addPropertySorting();
        ColumnViewerPreferences.create(viewer, PlanimodPreferences.getPreferenceStore(), PREFERENCE_COLUMNS);
    }

    /**
     * Create a new planner viewer.
     */
    protected PlannerViewer createPlannerViewer(Composite parent) {
        PlannerViewer viewer = new PlannerViewer(parent);
        // Sets the planner look
        viewer.getPlanner().setLook(new PlanimodPlannerLook());
        // A open listener to edit the event
        viewer.addOpenListener(new IOpenListener() {

            @Override
            public void open(OpenEvent event) {
                // JFace data binding, this action is already updated with the
                // current selection. We only need to run the action.
                NonAvailabilitiesViewPart.this.editNonAvailability.run();
            }
        });
        return viewer;
    }

    @Override
    public void deactivate() {
        this.addNonAvailability = null;
        this.editNonAvailability = null;
        this.longEventViewer = null;
        this.nextAction = null;
        this.previewAllAction = null;
        this.previousAction = null;
        this.printAllAction = null;
        this.todayAction = null;
        this.removeAction = null;
        this.viewer = null;
        super.deactivate();
    }

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

    /**
     * Populate the tool bar.
     */
    void fillToolBar() {
        PlanimodManagers managers = getSite().getService(PlanimodManagers.class);
        IToolBarManager toolbar = getSite().getToolBarManager();
        toolbar.removeAll();
        // Previous
        toolbar.add(this.previousAction = ChangeDateAction.previousAction(managers));
        // Today
        toolbar.add(this.todayAction = ChangeDateAction.todayAction(managers));
        // Next
        toolbar.add(this.nextAction = ChangeDateAction.nextAction(managers));
        // Separator
        toolbar.add(new Separator());
        // Add
        ActionContributionItem aci;
        toolbar.add(aci = new ActionContributionItem(this.addNonAvailability = new AddNonAvailabilityAction(managers, getSite(), this.viewer)));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        // Edit
        toolbar.add(aci = new ActionContributionItem(this.editNonAvailability = new EditNonAvailabilityAction(managers, getSite())));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        // Remove
        toolbar.add(aci = new ActionContributionItem(this.removeAction = new RemoveAction(managers, getSite())));
        this.removeAction.setConfirmationMessage(_("Êtes-vous sûr de vouloir supprimer l'absence sélectionnée ?"));
        this.removeAction
                .setConfirmationShortDetail(
                        _(
                                "À moins d'un erreur de manipulation, il n'est pas recommandé de supprimer une absence. Il est préférable de modifier la plage horaire d'une absence lorsque l'employé est de retour au travail."));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);
        // Separator
        toolbar.add(new Separator());
        // Print menu
        PrintActionMenuManager printMenu = new PrintActionMenuManager("NonAvailabilitiesViewPart.print");
        printMenu.add(this.printAllAction = new NonAvailabilityPrintAction(managers, getSite(), PrintAction.PRINT_ACTION, getSite().getMainWindow()));
        printMenu.add(this.previewAllAction = new NonAvailabilityPrintAction(managers, getSite(), PrintAction.PREVIEW_ACTION, getSite().getMainWindow()));
        toolbar.add(printMenu);
        // Add filter
        fillToolbarWithTextFilter();
    }
}
