package org.argosdic.util;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.argosdic.resource.ResourceManager;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * ExceptionHandler.java
 * @author Xavier Cho
 * @version $Revision: 1.2 $ $Date: 2003/10/03 07:04:09 $
 */
public class ExceptionHandler implements Window.IExceptionHandler {
    static Log log = LogFactory.getLog(ExceptionHandler.class);

    public void handleException(Throwable t) {
        handleException(null, t);
    }

    public static void handleException(String msg, Throwable t) {
        ResourceManager resources = ResourceManager.getInstance();
        try {
            if (msg == null) {
                msg = resources.getString("error.message.unknown"); //$NON-NLS-1$
            }
        } catch (Throwable th) {
            msg = "Unhandled exception has occurred."; //$NON-NLS-1$
        }

        try {
            StringWriter writer = new StringWriter();
            PrintWriter printer = new PrintWriter(writer);

            t.printStackTrace(printer);

            Status status =
                new Status(
                    Status.ERROR,
                    ExceptionHandler.class.getName(),
                    Status.OK,
                    writer.toString(),
                    t);

            MultiStatus multiStatus =
                new MultiStatus(
                    ExceptionHandler.class.getName(),
                    Status.OK,
                    msg,
                    t);
            multiStatus.add(status);

            Display display = Display.getCurrent();
            Shell parent = (display != null) ? display.getActiveShell() : null;
            String title = resources.getString("dialog.title.error"); //$NON-NLS-1$

            ErrorDialog.openError(parent, title, null, multiStatus);
        } catch (Throwable th) {
            log.warn("Unable to open error dialog : " + th.getMessage(), th); //$NON-NLS-1$
        }

        if (log.isErrorEnabled()) {
            log.error(msg, t);
        }
    }
}
