package cn.com.origin.autocodemanager.common.progress;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;

import cn.com.origin.autocodemanager.common.dialog.AbstractCodeSegmentDialog;
import cn.com.origin.autocodemanager.common.tree.AbstractCreateTreeView;
import cn.com.origin.autocodemanager.common.tree.AbstractTreeData;

/**
 * 任务执行进度条
 * 
 * @author wangjj
 * 
 */
public class ExpandProgressBar {

	private Shell shell;

	private ProgressMonitorDialog progressDialog;

	private ProgressBarListener progressbarListener; // 进度条事件监听器

	private AbstractTreeData[] codeDatas;

	private AbstractCreateTreeView createTreeView;
	AbstractCodeSegmentDialog codeDialog;

	public ExpandProgressBar(Shell shell, String title, AbstractCreateTreeView createTreeView, AbstractTreeData[] codeDatas) {
		this.shell = shell;
		this.createTreeView = createTreeView;
		this.codeDatas = codeDatas;
	}

	public ExpandProgressBar(Shell shell, String title, AbstractCodeSegmentDialog codeDialog, AbstractTreeData[] codeDatas) {
		this.shell = shell;
		this.codeDialog = codeDialog;
		this.codeDatas = codeDatas;
	}

	/**
	 * 打开导入进度条,并进行数据导入
	 * 
	 * @throws Exception
	 */
	public void expand() throws Exception {
		progressDialog = new ProgressMonitorDialog(shell);
		progressDialog.run(true, true, new IRunnableWithProgress() {
			public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
				try {
					shell.getDisplay().syncExec(new Runnable() {
						public void run() {
							try {
								if (codeDialog != null) {
									codeDialog.createOrgAutoCodeNodeChildren(codeDatas);
								} else {
									createTreeView.createOrgAutoCodeNodeChildren(codeDatas);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
					if (progressbarListener != null) {
						ProgressBarEvent event = new ProgressBarEvent(progressDialog);
						progressbarListener.completed(event);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					monitor.done();
				}
			}
		});
	}
}
