/**
 * 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.dialogs.IDialogConstants;
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.Employee;
import com.planimod.core.Task;
import com.planimod.core.Team;
import com.planimod.core.planif.GeneratePlanifContext;
import com.planimod.core.planif.GeneratePlanifException;
import com.planimod.core.planif.GeneratePlanifProgressMonitorStep;
import com.planimod.core.planif.ICallbackReason;
import com.planimod.core.planif.IGeneratePlanifProgressMonitor;
import com.planimod.core.planif.PreferedSeniorityCallbackReason;
import com.planimod.core.planif.PreferedSeniorityWithoutPrefTeamCallbackReason;
import com.planimod.core.planif.UnassignedTaskCallbackReason;
import com.planimod.ui.databinding.Converters;
import com.planimod.ui.theme.PlaySound;
import com.planimod.ui.theme.Resources;
import com.planimod.ui.viewers.EmployeeViewerUtils;

/**
 * This action is used to generate the planif. To run this action, user should sets the planif and week properties.
 * 
 * @author Patrik Dufresne
 */
public class GeneratePlanifAction extends Action {

    /**
     * Private implementation of the generate planif progress monitor. This implementation adapt a
     * {@link IProgressMonitor}.
     * 
     * @author Patrik Dufresne
     */
    class Monitor implements IGeneratePlanifProgressMonitor {

        boolean callbackContinue = false;

        /**
         * The progress monitor being adapted
         */
        private IProgressMonitor monitor;

        /**
         * Create a new monitor to adapt a {@link IProgressMonitor}
         * 
         * @param monitor
         *            the monitor to be adapted.
         */
        public Monitor(IProgressMonitor monitor) {
            this.monitor = monitor;
        }

        /**
         * This implementation convert the begin search into a begin task for the progress monitor.
         */
        @Override
        public void beginSearch(int nbStep) {
            this.monitor.beginTask(_("Recherche une solution..."), nbStep);
        }

        /**
         * This implementation display a dialog box to the user asking to continue the operation or not.
         * 
         * @param reason
         *            gives witch implementation of handleContinue will be called.
         */
        @Override
        public boolean callbackContinue(final ICallbackReason reason) {
            Display.getDefault().syncExec(new Runnable() {

                @Override
                public void run() {
                    Monitor.this.callbackContinue = handleContinue(reason);
                }
            });
            return this.callbackContinue;
        }

        /**
         * This operation call done.
         */
        @Override
        public void done() {
            this.monitor.done();
        }

        /**
         * True if the search should be stopped.
         */
        @Override
        public boolean isCanceled() {
            return this.monitor.isCanceled();
        }

        @Override
        public void setStep(GeneratePlanifProgressMonitorStep step) {
            String name = "";
            switch (step) {
            case CREATE_VARIABLES:
                name = _("Création du problème.");
                break;
            case MAXIMIZE_ASSIGNED_TASK:
                name = _("Calcul du nombre maximum de tâches pouvant être affectées.");
                break;
            case MINIMIZE_EMPLOYEE:
                name = _("Calcul du nombre maximum de tâches pouvant être affectées.");
                break;
            case MAXIMIZE_SENIOR:
                name = _("Force l'utilisation d'employé avec le plus de séniorité.");
                break;
            case MAXIMIZE_PREFERENCES:
                name = _("Applique les préférences des employés.");
                break;
            case MAXIMIZE_PREFERRED_SENIORITIES:
                name = _("Force l'utilisation d'employé avec l'ancienneté privilégiée.");
                break;
            case CHECK_FEASIBLE:
                name = _("Vérifie que le problème est faisable.");
                break;
            case MINIMIZE_SWAPPABLE_TASK:
                name = _("Minimise le nombre de tâches permutables.");
                break;
            }
            this.monitor.subTask(name);
        }

        /**
         * This implementation call the adapted class.
         */
        @Override
        public void worked(int work) {
            this.monitor.worked(work);
        }
    }

    /**
     * Return the employee's name or "unknown" if the employee object is null.
     * 
     * @param employee
     *            the object
     * @return the employee's name or null
     */
    private static String getName(Employee employee) {
        return employee != null ? EmployeeViewerUtils.getName(employee) : _("Inconnu");
    }

    /**
     * Return the team's name or "unknown" if the employee object is null.
     * 
     * @param team
     *            the object
     * @return the team's name or null
     */
    private static String getName(Team team) {
        return team != null ? Converters.removeFrontNumber().convert(team.getName()).toString() : _("Inconnue");
    }

    /**
     * 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
     *            the generate planif context to be used.
     */
    public GeneratePlanifAction(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(_("Générer Planif."));
        setToolTipText(_("Générer planification du mouvement de main d'oeuvre"));
        setImageDescriptor(Resources.getImageDescriptor(Resources.ICON_GENERATE_PLANIF_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.planifContext = null;
        }
    }

    private <T extends Throwable> T findException(Throwable e, Class<T> cls) {
        if (e.getCause() != null) {
            if (cls.isAssignableFrom(e.getCause().getClass())) {
                return (T) e.getCause();
            }
            return findException(e.getCause(), cls);
        }
        return null;
    }

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

    /**
     * Opens a message window DetailYesNoQuestion
     * 
     * @param reason
     *            gives witch implementation of handleContinue will be used.
     */

    protected boolean handleContinue(ICallbackReason reason) {
        String title = _("Générer Planif.");
        String message = "";
        String shortDetail = "";
        if (reason instanceof UnassignedTaskCallbackReason) {
            message = _("Voulez-vous continuer?");
            shortDetail = _("Certaines tâches ne peuvent être affectées à un employé. Il est possible qu'il y ait trop de production pour le nombre d'employés disponibles. Voulez-vous poursuivre ?");
        } else if (reason instanceof PreferedSeniorityCallbackReason) {
            String employeeName = getName(((PreferedSeniorityCallbackReason) reason).getEmployee());
            String teamName = getName(((PreferedSeniorityCallbackReason) reason).getTeam());
            message = _("Voulez-vous continuer?");
            shortDetail = _("L'employé avec ancienneté privilégiée %s ne pourra pas travailler sur son équipe préférée : %s.", employeeName, teamName);
        } else if (reason instanceof PreferedSeniorityWithoutPrefTeamCallbackReason) {
            String employeeName = getName(((PreferedSeniorityWithoutPrefTeamCallbackReason) reason).getEmployee());
            message = _("Voulez-vous continuer?");
            shortDetail = _("L'employé avec ancienneté privilégiée %s n'a pas d'équipe préférée.", employeeName);
        }
        // Play a sound before opening the dialog to notify the user.
        PlaySound.playNotify();
        // Show the dialog
        DetailMessageDialog dlg = DetailMessageDialog.openDetailYesNoQuestion(this.shell.getShell(), title, message, shortDetail, null);
        return dlg.getReturnCode() == IDialogConstants.YES_ID;
    }

    private void handleException(InvocationTargetException e) {
        final GeneratePlanifException e1 = findException(e, GeneratePlanifException.class);
        if (e1 != null) {
            Display.getDefault().asyncExec(new Runnable() {

                @Override
                public void run() {
                    handleGeneratePlanifException(e1);
                }
            });
            return;
        }
        final ManagerException e2 = findException(e, ManagerException.class);
        if (e2 != null) {
            Display.getDefault().asyncExec(new Runnable() {

                @Override
                public void run() {
                    handleManagerException(e2);
                }
            });
        }
    }

    /**
     * Display an error message for the given exception;
     * 
     * @param e
     */
    protected void handleGeneratePlanifException(GeneratePlanifException e) {
        // Compute the employee name
        Employee employee = e.getEmployee();
        String employeeName = getName(employee);
        // Compute the task name
        // TODO Create a utility class to generate a description for the task.
        Task task = e.getTask();
        String taskName = task != null ? task.getPosition().getName() : _("Inconnue");
        Team team = e.getTeam();
        String teamName = getName(team);
        // Compute the reason description
        int reason = e.getReason();
        String shortDetail = null;
        switch (reason) {
        case GeneratePlanifException.EMPLOYEE_LOCKED_UNAVAIL_OR_UNQUALIFY:
            shortDetail = _(
                    "Un employé, %s, est verrouillé sur la tâche %s alors qu'il n'est pas disponible pour cette tâche. Vous devez déverrouiller cet employé pour générer une planification.",
                    employeeName,
                    taskName);
            // TODO Provide a default action to fix the problem.
            break;
        case GeneratePlanifException.STARTING_UNFEASIBLE:
            shortDetail = _("Les données de départ ne permettent pas de trouver une solution. Vérifier qu'un employé n'est pas verrouillé sur deux tâches conflictuelles. P.ex.: Un employé verrouillé dans deux équipes différentes ou deux tâches du même quart de travail.");
            break;
        case GeneratePlanifException.UNFEASIBLE:
            shortDetail = _("Il a été impossible de trouver une solution.", employeeName, teamName);
            break;
        default:
            shortDetail = _("Aucune raison n'a été fournie.");
        }
        /*
         * Display the message dialog.
         */
        DetailMessageDialog
                .openDetailWarning(this.shell.getShell(), _("Une erreur s'est produite"), _("Impossible de générer une planification."), shortDetail);
    }

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

    /**
     * This implementation run the generate planif in a runnable context.
     */
    @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 {
                    try {
                        GeneratePlanifAction.this.planifContext.searchSolution(new Monitor(monitor));
                    } catch (final ManagerException e) {
                        GeneratePlanifException e2 = findException(e, GeneratePlanifException.class);
                        if (e2 != null && e2.getReason() == GeneratePlanifException.CANCEL_BY_USER) {
                            throw new InterruptedException();
                        }
                        throw new InvocationTargetException(e);
                    }
                    monitor.done();
                    // Play a sound to notify the user
                    PlaySound.playNotify();
                }
            });
        } catch (InvocationTargetException e) {
            // An error occurred during the process let handle it properly
            handleException(e);
        } catch (InterruptedException e) {
            // Operation cancel by user nothing to do
        }
    }
}
