/*
 * 作成日: 2008/08/05
 * 著作権: Copyright (c) 2005 ZIGEN
 * ライセンス：Eclipse Public License - v 1.0
 * 原文：http://www.eclipse.org/legal/epl-v10.html
 */
package zigen.plugin.db.ext.s2jdbc;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import zigen.plugin.db.DbPluginConstant;
import zigen.plugin.db.JobException;
import zigen.plugin.db.core.StringUtil;


/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {
	
	public static String LINE_SEP = System.getProperty("line.separator"); //$NON-NLS-1$
	
	public static final String TITLE = "ZIGEN's DBViewer Plugin"; //$NON-NLS-1$
	
	public static final String VERSION = "1.0.0 release 2008/09/01"; //$NON-NLS-1$
	
	public static final String PLUGIN_ID = "zigen.plugin.db.ext.s2jdbc"; //$NON-NLS-1$
	
	private static Activator plugin;
	
	private String defaultProject = null;
	
	// private String defaultSuperClass = null;
	

	/**
	 * The constructor
	 */
	public Activator() {
		plugin = this;
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}
	
	private static String getPluginId() {
		return getDefault().getBundle().getSymbolicName();
	}
	
	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}
	
	// パッケージ選択ダイアログOpen時の初期展開プロジェクト取得
	public String getDefaultProject() {
		return defaultProject;
	}
	
	// パッケージ選択ダイアログOpen時の初期展開プロジェクトの設定
	public void setDefaultProject(String defaultProject) {
		this.defaultProject = defaultProject;
	}
	
	public IWorkbenchPage getPage() {
		IWorkbench workbench = PlatformUI.getWorkbench();
		IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
		return window.getActivePage();
	}
	
	public Shell getShell() {
		IWorkbench workbench = PlatformUI.getWorkbench();
		IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
		return window.getShell();
	}
	
	public static void log(String message, Exception e) {
		IStatus status = new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, message, e);
		getDefault().getLog().log(status);
	}
	
	public static void log(Exception e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		String message = stringWriter.getBuffer().toString();
		log(message, e);
		
		// for debug
		if (e != null)
			e.printStackTrace();
	}
	
	/**
	 * メッセージ表示（情報ダイアログ）
	 * 
	 * @param message
	 */
	public void showInformationMessage(String message) {
		MessageDialog.openInformation(getShell(), DbPluginConstant.TITLE, message);
	}
	
	/**
	 * メッセージ表示（警告ダイアログ）
	 * 
	 * @param message
	 */
	public void showWarningMessage(String message) {
		MessageDialog.openWarning(getShell(), DbPluginConstant.TITLE, message);
	}
	
	/**
	 * 確認ダイアログ
	 * 
	 * @param message
	 */
	public boolean confirmDialog(String message) {
		return MessageDialog.openConfirm(getShell(), DbPluginConstant.TITLE, message);
	}
	
	public static void log(String message, Throwable e) {
		IStatus status = new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, message, e);
		getDefault().getLog().log(status);
	}
	
	public static void log(String message) {
		log(message, null);
	}
	
	public static void log(Throwable e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		String message = stringWriter.getBuffer().toString();
		log(message, e);
		
		// for debug
		if (e != null)
			e.printStackTrace();
	}
	
	public static void log(IStatus status) {
		getDefault().getLog().log(status);
	}
	
	
	private static String getErrorMessage(Throwable throwable) {
		if (throwable != null) {
			String msg = throwable.getMessage();
			if (msg == null) {
				return getErrorMessage(throwable.getCause());
			} else {
				return msg;
			}
		} else {
			// "スタックトレースを確認してください" メッセージ
			return Messages.getString("Activator.ConfrimStatckTraceMessage"); //$NON-NLS-1$
		}
	}
	
	private static String getFirstLineMessage(String message) {
		StringUtil.convertLineSep(message); // \n で改行を統一する
		int pos = message.indexOf("\n"); //$NON-NLS-1$
		if (pos > 0) {
			return message.substring(0, pos);
		} else {
			return message;
		}
		
	}
	
	static IStatus createErrorStatus(Throwable throwable) {
		String msg = getErrorMessage(throwable);
		String lineMsg = getFirstLineMessage(msg);
		
		// MultiStatus mStatus = new MultiStatus(getPluginId(), IStatus.ERROR, lineMsg, new Exception(Messages.getString("DbPlugin.1"))); //$NON-NLS-1$
		// MultiStatus mStatus = new MultiStatus(getPluginId(), IStatus.ERROR, lineMsg, null); //$NON-NLS-1$
		// mStatus.add(new Status(IStatus.ERROR, getPluginId(), IStatus.OK, msg, null));
		// return mStatus;
		return new Status(IStatus.ERROR, getPluginId(), IStatus.OK, lineMsg, throwable);
		
	}
	
	public static IStatus createWarningStatus(Throwable throwable) {
		return createWarningStatus(-1, throwable);
	}
	
	static IStatus createWarningStatus(int errorCode, Throwable throwable) {
		String msg = getErrorMessage(throwable);
		msg = getFirstLineMessage(msg);
		return new Status(IStatus.WARNING, getPluginId(), errorCode, msg, null);
	}
	
	public void showErrorDialog(Throwable throwable) {
		// for Debug
		if (throwable != null) {
			throwable.printStackTrace();
		}
		
		String message = Messages.getString("Activator.ErrorMessage"); //$NON-NLS-1$
		IStatus status = null;
		
		if (throwable instanceof JobException) {
			JobException je = (JobException) throwable;
			Throwable cause = je.getCause();
			if (cause instanceof SQLException) {
				status = createErrorStatus(cause);
			} else {
				status = createErrorStatus(cause);
				
			}
		} else {
			
			if (throwable instanceof SQLException) {
				status = createErrorStatus(throwable);
			} else {
				status = createErrorStatus(throwable);
			}
		}
		ErrorDialog.openError(getShell(), DbPluginConstant.TITLE, message, status);
	}
}
