/**
 * 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.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;

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

/**
 * Action to edit a non-availability event.
 * 
 * @author Patrik Dufresne
 * 
 */
public class EditProductionEventAction extends Action {

    /**
     * Property name for planif state (value <code>"planif"</code> ).
     */
    public static final String PLANIF = "planif";
    /**
     * Property name for shift (value <code>"shift"</code> ).
     */
    public static final String SHIFT = "shift";

    /**
     * Static function to edit a shift event.
     * 
     * @param managers
     *            the managers
     * @param shell
     *            the parent shell
     * @param event
     *            the calendar event to edit
     */
    public static void edit(PlanimodManagers managers, Shell shell, Shift event) {
        // Query the database to get the list of production event matching the
        // planif and the given shift event
        List<ProductionEvent> prodEvents;
        try {
            prodEvents = managers.getProductionEventManager().listByShift(event);
        } catch (ManagerException e) {
            PlanimodPolicy.showException(e);
            return;
        }

        // Open the dialog
        EditProductionEventDialog dlg = new EditProductionEventDialog(shell, managers);
        dlg.setShift(event);
        dlg.setProductionEvents(prodEvents);

        // Open the dialog to edit the events
        if (dlg.open() != Window.OK) {
            // Cancel by user
            return;
        }

        // Add & delete the events
        Set<ProductionEvent> newProductionEvents = new HashSet<ProductionEvent>(dlg.getProductionEvents());
        List<ProductionEvent> toDelete = new ArrayList<ProductionEvent>();
        for (ProductionEvent prodEvent : prodEvents) {
            // Check if the event already exists, or is new
            if (newProductionEvents.contains(prodEvent)) {
                newProductionEvents.remove(prodEvent);
            } else {
                toDelete.add(prodEvent);
            }
        }
        for (ProductionEvent calEvent : newProductionEvents) {
            calEvent.setShift(event);
        }

        // Save the events
        try {
            managers.getProductionEventManager().add(newProductionEvents);
            managers.getProductionEventManager().remove(toDelete);
        } catch (ManagerException e) {
            PlanimodPolicy.showException(e);
            return;
        }
    }

    /**
     * Managers to use
     */
    private PlanimodManagers managers;

    /**
     * Shell provider.
     */
    private IShellProvider shellProvider;

    /**
     * The current shift event.
     */
    private Shift shift;

    /**
     * Create a new action.
     * 
     * @param managers
     * @param provider
     * @param selectionProvider
     */
    public EditProductionEventAction(PlanimodManagers managers, IShellProvider provider) {
        this.managers = managers;
        this.shellProvider = provider;
        setText(_("Modifier"));
        setToolTipText(_("Modifier une production"));
        setImageDescriptor(Resources.getImageDescriptor(Resources.ICON_EDIT_16));
        setEnabled(canRun());
    }

    /**
     * This function is used to determine if the action can be run.
     * 
     * @return True if the planif and the shift event are define.
     */
    protected boolean canRun() {
        return this.shift != null;
    }

    /**
     * Returns the current shift event.
     * 
     * @return
     */
    public Shift getShift() {
        return this.shift;
    }

    /**
     * This implementation open a dialog to edit the event.
     */
    @Override
    public void run() {
        if (!canRun()) {
            return;
        }
        edit(this.managers, this.shellProvider.getShell(), this.shift);
    }

    /**
     * Sets the shift event value for this action.
     * 
     * @param shift
     */
    public void setShift(Shift shift) {
        if ((this.shift == null && shift != null)
                || (this.shift != null && shift == null)
                || (this.shift != null && shift != null && !shift.equals(this.shift))) {
            Object oldDescription = this.shift;
            this.shift = shift;
            firePropertyChange(SHIFT, oldDescription, this.shift);
            setEnabled(canRun());
        }
    }
}