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

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

import java.io.PrintWriter;
import java.io.StringWriter;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.widgets.Display;

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

public class DuplicateProductAction extends Action {

    /**
     * Product property name
     */
    public static final String PRODUCT = "product";
    /**
     * The product to be duplicated.
     */
    private Product product;
    /**
     * Managers to used to add the element.
     */
    private PlanimodManagers managers;
    /**
     * Selection provider.
     */
    private ISelectionProvider selectionProvider;
    /**
     * Shell provider.
     */
    private IShellProvider shellProvider;

    /**
     * Create a new action.
     * 
     * @param managers
     *            the managers to be used
     * @param shellProvider
     *            a shell provider in case the action need to display a message box.
     * @param selectionProvider
     * 
     */
    public DuplicateProductAction(PlanimodManagers managers, IShellProvider shellProvider, ISelectionProvider selectionProvider) {
        if (managers == null || shellProvider == null) {
            throw new NullPointerException();
        }
        this.managers = managers;
        this.shellProvider = shellProvider;
        this.selectionProvider = selectionProvider;
        setText(_("Recopier"));
        setToolTipText(_("Effectue une copie du produit sélectionné"));
        setImageDescriptor(Resources.getImageDescriptor(Resources.ICON_DUPLICATE_16));
        setEnabled(canRun());
    }

    /**
     * This implementation always return true.
     * 
     * @see net.ekwos.gymkhana.ui.views.AbstractAddAction#canCreateObject()
     */
    protected boolean canRun() {
        return (product != null);
    }

    /**
     * Returns the product.
     * 
     * @return
     */
    public Product getProduct() {
        return this.product;
    }

    /**
     * This implementation run the copy of productManager.
     */
    @Override
    public void run() {
        if (!canRun()) {
            return;
        }
        Product newProduct;
        try {
            newProduct = managers.getProductManager().copy(product);
        } catch (ManagerException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            DetailMessageDialog.openDetailWarning(
                    this.shellProvider.getShell(),
                    getText(),
                    _("Impossible de copier le produit."),
                    _("Une erreur s'est produite lors de la copie du produit."),
                    e);
            return;
        }
        // Select object in the viewer
        final Product finalProduct = newProduct;
        Display.getDefault().asyncExec(new Runnable() {
            @Override
            public void run() {
                selectObjects(finalProduct);
            }
        });
    }

    /**
     * Called to select into the selection provider if define.
     * 
     * @param list
     */
    protected void selectObjects(Product product) {
        if (this.selectionProvider instanceof StructuredViewer) {
            ((StructuredViewer) this.selectionProvider).setSelection(new StructuredSelection(product), true);
        } else if (this.selectionProvider != null) {
            this.selectionProvider.setSelection(new StructuredSelection(product));
        }
    }

    /**
     * Sets the product.
     * 
     * @param product
     */
    public void setProduct(Product product) {
        firePropertyChange(PRODUCT, this.product, this.product = product);
        setEnabled(canRun());
    }
}