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

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

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;

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.swt.widgets.Display;

import com.patrikdufresne.jface.dialogs.DetailMessageDialog;
import com.patrikdufresne.managers.ManagerException;
import com.planimod.core.planif.GeneratePlanifContext;
import com.planimod.ui.PlanimodPolicy;
import com.planimod.ui.theme.Resources;

/**
 * This action is used to create tasks for the current planif context without computing the planif. This is useful to
 * lock employee before generating the planif.
 * 
 * @author Patrik Dufresne
 * 
 */
public class CreateTasksAction extends Action {

    /**
     * The runnable context to display the action progress.
     */
    private IRunnableContext context;

    /**
     * Listen to dirty field
     */
    private PropertyChangeListener listener = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (GeneratePlanifContext.DIRTY.equals(evt.getPropertyName())) {
                setEnabled(canRun());
            }
        }
    };

    /**
     * The context used to generate a planif.
     */
    GeneratePlanifContext planifContext;

    /**
     * The shell provider to display message dialog.
     */
    private IShellProvider shell;

    /**
     * Create a new action.
     * 
     * @param context
     */
    public CreateTasksAction(GeneratePlanifContext planifContext, IShellProvider shell, IRunnableContext context) {
        super();
        if (planifContext == null) {
            throw new NullPointerException("planifContext");
        }
        if (context == null || shell == null) {
            throw new NullPointerException();
        }
        this.shell = shell;
        this.planifContext = planifContext;
        this.planifContext.addPropertyChangeListener(this.listener);

        this.context = context;

        setText(_("Créer tâches"));
        setToolTipText(_("Permet de créer les tâches d'une planification sans effectuer de calculs."));
        setImageDescriptor(Resources.getImageDescriptor(Resources.ICON_CREATE_TASKS_16));
        setEnabled(canRun());
    }

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

    /**
     * Should be called to dispose this action
     */
    public void dispose() {
        if (this.planifContext != null) {
            this.planifContext.removePropertyChangeListener(this.listener);
        }
        this.context = null;
        this.listener = null;
        this.planifContext = null;
        this.shell = null;
    }

    /**
     * Return the current generate planif context for this action.
     * 
     * @return
     */
    public GeneratePlanifContext getGeneratePlanifContext() {
        return this.planifContext;
    }

    /**
     * Display an error message for the given exception.
     * 
     * @param e
     */
    protected void handleManagerException(ManagerException e) {
        String title = _("Créer tâches");
        String message = _("Impossible de générer une planification.");
        String shortDetail = _("Aucune raison n'a été fournie.");
        DetailMessageDialog.openDetailWarning(this.shell.getShell(), title, message, shortDetail, e);
    }

    /**
     * This implementation run the creation of the task.
     */
    @Override
    public void run() {
        if (this.context == null) {
            return;
        }

        try {
            this.context.run(true, true, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                    // Start the task
                    monitor.beginTask(_("Création des tâches..."), IProgressMonitor.UNKNOWN);
                    try {
                        CreateTasksAction.this.planifContext.createTasks();
                    } catch (final ManagerException e) {
                        Display.getDefault().asyncExec(new Runnable() {
                            @Override
                            public void run() {
                                handleManagerException(e);
                            }
                        });
                    }
                    monitor.done();
                }
            });
        } catch (InvocationTargetException e) {
            PlanimodPolicy.showException(e);
        } catch (InterruptedException e) {
            PlanimodPolicy.showException(e);
        }
    }

}
