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

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

import java.util.Date;

import org.eclipse.core.databinding.BindingProperties;
import org.eclipse.core.databinding.beans.BeanProperties;
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.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.IOpenListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.swt.SWT;
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.PropertyViewerComparator;
import com.patrikdufresne.planner.Planner;
import com.patrikdufresne.planner.databinding.PlannerProperties;
import com.patrikdufresne.planner.databinding.PlannerViewerUpdater;
import com.patrikdufresne.planner.viewer.PlannerViewer;
import com.planimod.core.AbstractCalendarEvent;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.ProductionEvent;
import com.planimod.core.Shift;
import com.planimod.core.Team;
import com.planimod.core.comparators.ShiftComparators;
import com.planimod.ui.databinding.Converters;
import com.planimod.ui.databinding.DateColorControlStyleSupport;
import com.planimod.ui.databinding.manager.ShiftComputedSet;
import com.planimod.ui.preference.PlanimodPreferences;
import com.planimod.ui.viewers.planner.ObservableMapPlannerLabelProviderWithColor;
import com.planimod.ui.viewers.planner.PlanimodPlannerLook;
import com.planimod.ui.views.AbstractViewPart;
import com.planimod.ui.views.ChangeDateAction;

/**
 * This view part display planif information in a planner view.
 * 
 * @author Patrik Dufresne
 * 
 */
public class ProductionViewPart extends AbstractViewPart {
    /**
     * Dot value (.)
     */
    private static final String DOT = ".";
    /**
     * The part id.
     */
    public static final String ID = "comp.planimod.ui.views.production.ProductionViewPart";

    private DuplicateProductionEventAction duplicateProductionEventAction;
    protected EditProductionEventAction editProductionAction;

    private ChangeDateAction nextAction;

    private ChangeDateAction previousAction;
    private RemoveAllProductionEventAction removeProductionEventAction;
    private ChangeDateAction todayAction;
    private PlannerViewer viewer;

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

    /**
     * This implementation add tool bar action and bin the view.
     */
    @Override
    public void activate(Composite parent) {

        // Create the viewer
        this.viewer = createPlannerViewer(parent);
        this.viewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        // Populate the tool bar
        fillToolBar();

        // Create binding
        bind();

    }

    /**
     * Binds the planner date selection to a shared state.
     */
    @Override
    protected void bindValues() {
        super.bindValues();

        /*
         * Get the states.
         */
        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 = this.viewer.getPlanner();
        getDbc().bindValue(PlannerProperties.dateSelection().observe(planner), date);
        IObservableValue start = PlannerProperties.startDateValue().observe(planner);
        IObservableValue end = PlannerProperties.endDateValue().observe(planner);

        /*
         * Bind the viewer.
         */
        IObservableSet shifts = new ShiftComputedSet(getSite().getService(PlanimodManagers.class), start, end);
        IObservableMap shiftLabels = new ShiftProductionEventObservableMap(getSite().getService(PlanimodManagers.class), shifts);
        IObservableMap shiftStart = BeanProperties.value(AbstractCalendarEvent.class, AbstractCalendarEvent.START_DATE, Date.class).observeDetail(shifts);
        IObservableMap shiftEnd = BeanProperties.value(AbstractCalendarEvent.class, AbstractCalendarEvent.END_DATE, Date.class).observeDetail(shifts);
        IObservableMap color = BeanProperties
                .value(Shift.class, Shift.TEAM + DOT + Team.COLOR)
                .value(BindingProperties.convertedValue(Converters.StringToRGB()))
                .observeDetail(shifts);

        this.viewer.setContentProvider(new ObservableSetContentProvider(new PlannerViewerUpdater(this.viewer)));
        this.viewer.setLabelProvider(new ObservableMapPlannerLabelProviderWithColor(shiftLabels, shiftStart, shiftEnd, color));
        this.viewer.setComparator(new PropertyViewerComparator(ShiftComparators.byHourAndTeam()));
        this.viewer.setInput(shifts);

        IObservableValue selectedShift = ViewersObservables.observeSingleSelection(this.viewer);

        /*
         * Bind the planner background color.
         */
        DateColorControlStyleSupport.create(this.viewer.getPlanner(), date);

        /*
         * 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);

        // Duplicate action
        getDbc()
                .bindValue(
                        JFaceProperties
                                .value(DuplicateProductionEventAction.class, DuplicateProductionEventAction.DATE, DuplicateProductionEventAction.DATE)
                                .observe(this.duplicateProductionEventAction),
                        date);

        // Edit action
        getDbc()
                .bindValue(
                        JFaceProperties
                                .value(EditProductionEventAction.class, ProductionEvent.SHIFT, EditProductionEventAction.SHIFT)
                                .observe(this.editProductionAction),
                        selectedShift);

        // Remove action
        getDbc()
                .bindValue(
                        JFaceProperties
                                .value(RemoveAllProductionEventAction.class, "date", RemoveAllProductionEventAction.DATE)
                                .observe(this.removeProductionEventAction),
                        date);

    }

    /**
     * This implementation create a planner viewer.
     */
    protected PlannerViewer createPlannerViewer(Composite parent) {

        PlannerViewer viewer = new PlannerViewer(parent);

        // sets planner look.
        viewer.getPlanner().setLook(new PlanimodPlannerLook());

        /**
         * Add a listener to edit the events.
         */
        viewer.addOpenListener(new IOpenListener() {
            @Override
            public void open(OpenEvent event) {
                ProductionViewPart.this.editProductionAction.run();
            }
        });

        return viewer;
    }

    /**
     * This implementation free allocated resources.
     */
    @Override
    public void deactivate() {
        try {
            this.duplicateProductionEventAction = null;
            this.editProductionAction = null;
            this.nextAction = null;
            this.previousAction = null;
            this.removeProductionEventAction = null;
            this.todayAction = null;
            this.viewer = null;
        } finally {
            super.deactivate();
        }
    }

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

    void fillToolBar() {
        PlanimodManagers managers = getSite().getService(PlanimodManagers.class);
        IToolBarManager toolbar = getSite().getToolBarManager();
        /*
         * Date navigation
         */
        this.previousAction = ChangeDateAction.previousAction(managers);
        this.todayAction = ChangeDateAction.todayAction(managers);
        this.nextAction = ChangeDateAction.nextAction(managers);
        toolbar.add(this.previousAction);
        toolbar.add(this.todayAction);
        toolbar.add(this.nextAction);

        /*
         * Separator
         */
        toolbar.add(new Separator());

        /*
         * Edit events
         */
        ActionContributionItem aci;
        toolbar.add(aci = new ActionContributionItem(this.editProductionAction = new EditProductionEventAction(managers, getSite())));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);

        /*
         * Remove events
         */
        toolbar
                .add(
                        aci = new ActionContributionItem(
                                this.removeProductionEventAction = new RemoveAllProductionEventAction(managers, getSite(), getSite().getMainWindow())));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);

        /*
         * Copy events
         */
        toolbar
                .add(
                        aci = new ActionContributionItem(
                                this.duplicateProductionEventAction = new DuplicateProductionEventAction(managers, getSite(), getSite().getMainWindow())));
        aci.setMode(ActionContributionItem.MODE_FORCE_TEXT);

    }

}
