/**
 * 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.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.window.Window;

import com.patrikdufresne.managers.ManagerException;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.ProductionEvent;
import com.planimod.core.Shift;
import com.planimod.core.TimeRanges;
import com.planimod.ui.PlanimodPolicy;
import com.planimod.ui.theme.Resources;

/**
 * This action is used to duplicate the production events from one week to the other week.
 * 
 * @author Patrik Dufresne
 * 
 */
public class DuplicateProductionEventAction extends Action {

    /**
     * Property name of an action's date (value <code>"date"</code>). The date property is used to know the time range
     * to be printed by this action.
     */
    public static final String DATE = "date";
    /**
     * The runnable context to display the action progress.
     */
    private IRunnableContext context;
    /**
     * Define the date value.
     */
    private Date date;

    /**
     * The managers to use.
     */
    private PlanimodManagers managers;

    private IShellProvider shellProvider;

    /**
     * Create a new action.
     * 
     * @param managers
     *            the managers to be used
     * @param shellProvider
     *            a shell provider used to open dialog
     * @param context
     *            a runnable context to run the operation
     */
    public DuplicateProductionEventAction(PlanimodManagers managers, IShellProvider shellProvider, IRunnableContext context) {
        super();
        if (shellProvider == null || managers == null || context == null) {
            throw new NullPointerException();
        }
        this.shellProvider = shellProvider;
        this.managers = managers;
        this.context = context;
        setText(_("Recopier"));
        setToolTipText(_("Effectue une copie des événements de production"));
        setImageDescriptor(Resources.getImageDescriptor(Resources.ICON_DUPLICATE_16));
        setEnabled(canRun());
    }

    /**
     * Returns True if the action can be run.
     * 
     * @return
     */
    protected boolean canRun() {
        return this.date != null;
    }

    /**
     * Returns the current date state or null if not define.
     * 
     * @return the date state or null
     */
    public Date getDate() {
        return this.date;
    }

    /**
     * This implementation run the generate planif in a runnable context.
     */
    @Override
    public void run() {
        // Check the planif and date value
        if (this.date == null) {
            return;
        }

        // Open a dialog to ask the user what to copy.
        DuplicateProductionEventDialog dlg = new DuplicateProductionEventDialog(this.shellProvider.getShell(), this.managers);
        dlg.setDate(this.date);
        if (dlg.open() == Window.CANCEL || dlg.getDate() == null) {
            // Operation cancel by user
            return;
        }
        final Date selectedDate = dlg.getDate();

        try {
            this.context.run(true, true, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    runDuplicate(monitor, selectedDate);
                }
            });
        } catch (InvocationTargetException e) {
            PlanimodPolicy.showException(e);
        } catch (InterruptedException e) {
            PlanimodPolicy.showException(e);
        }
    }

    /**
     * Called by the runnable with progress to run the generate planif.
     */
    protected void runDuplicate(IProgressMonitor monitor, Date selectedDate) {

        // Start the task
        monitor.beginTask(_("Copie des événements de production..."), IProgressMonitor.UNKNOWN);

        // Since the production event copy will only copy the shift that are
        // references, this action will enforce the copy of every shift events.
        try {
            int firstDayOfWeek = this.managers.getApplicationSettingManager().getFirstDayOfWeek();
            Date startSource = TimeRanges.getWeekStart(selectedDate, firstDayOfWeek);
            Date endSource = TimeRanges.getWeekEnd(selectedDate, firstDayOfWeek);
            Date destDate = TimeRanges.getWeekStart(this.date, firstDayOfWeek);
            List<Shift> shifts = this.managers.getShiftManager().list(startSource, endSource);
            List<ProductionEvent> events = this.managers.getProductionEventManager().list(startSource, endSource);
            this.managers.getProductionEventManager().copy(shifts, events, destDate, true);
        } catch (ManagerException e) {
            PlanimodPolicy.showException(e);
        }
        monitor.done();
    }

    /**
     * Sets the destination date (week).
     * 
     * @param date
     *            the new date or null
     */
    public void setDate(Date date) {
        if ((this.date == null && date != null) || (this.date != null && date == null) || (this.date != null && date != null && !date.equals(this.date))) {
            Date oldDescription = this.date;
            this.date = date;
            firePropertyChange(DATE, oldDescription, this.date);
            setEnabled(canRun());
        }
    }

}
