/**
 * 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.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.IShellProvider;

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

public class RemoveAllProductionEventAction 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";
    private IRunnableContext context;

    /**
     * Define the date value.
     */
    private Date date;

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

    public RemoveAllProductionEventAction(PlanimodManagers managers, IShellProvider shellProvider, IRunnableContext context) {
        super();
        if (shellProvider == null || managers == null || context == null) {
            throw new NullPointerException();
        }
        this.managers = managers;
        this.shellProvider = shellProvider;
        this.context = context;
        setText(_("Tout supprimer"));
        setToolTipText(_("Supprime tous les événements de production"));
        setImageDescriptor(Resources.getImageDescriptor(Resources.ICON_LIST_REMOVE_ALL_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;
        }

        // Confirmation
        DetailMessageDialog dlg = DetailMessageDialog
                .openDetailYesNoQuestion(
                        this.shellProvider.getShell(),
                        _("Tout supprimer"),
                        _("Êtes-vous sûr de vouloir supprimer toute la production de la semaine en cours ?"),
                        _("Cette opération permet de supprimer tous les événements de production pour la semaine actuellement affichée. Ceci aura pour effet de supprimer également toutes les tâches de cette même semaine."),
                        null);
        if (dlg.getReturnCode() != IDialogConstants.YES_ID) {
            return;
        }

        // To ensure a proper copy of the production event week, ceil all the
        // date.
        try {
            this.context.run(true, true, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    runRemove(monitor);
                }
            });
        } catch (InvocationTargetException e) {
            PlanimodPolicy.showException(e);
        } catch (InterruptedException e) {
            PlanimodPolicy.showException(e);
        }
    }

    protected void runRemove(IProgressMonitor monitor) {

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

        // Run the copy
        try {
            Date start = TimeRanges.getWeekStart(this.date, this.managers.getApplicationSettingManager().getFirstDayOfWeek());
            Date end = TimeRanges.getWeekEnd(this.date, this.managers.getApplicationSettingManager().getFirstDayOfWeek());
            List<ProductionEvent> events = this.managers.getProductionEventManager().list(start, end);
            this.managers.getProductionEventManager().remove(events);
        } catch (ManagerException e) {
            PlanimodPolicy.showException(e);
        }
        monitor.done();

    }

    /**
     * Sets the date to define the time range to be printed.
     * 
     * @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());
        }
    }

}
