package net.kldp.logviewer;

import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.update.search.BackLevelFilter;
import org.eclipse.update.search.EnvironmentFilter;
import org.eclipse.update.search.UpdateSearchRequest;
import org.eclipse.update.search.UpdateSearchScope;
import org.eclipse.update.ui.UpdateJob;
import org.eclipse.update.ui.UpdateManagerUI;

/**
 * 업데이트를 검색한다
 * 
 * @author hangumkj
 *
 */
public class NewExtensionAction extends Action implements IAction {
	private IWorkbenchWindow window;
	
	public NewExtensionAction(IWorkbenchWindow window) {
		this.window = window;
		
		setId("net.kdlp.logviewer.NewExtension");
		setText("&Update");
		setToolTipText("LogViewer의 업데이트를 검색합니다.");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, IImageKeys.LOG_UPDATE));		
	}

	public void run() {
		BusyIndicator.showWhile(window.getShell().getDisplay(), new Runnable() {
			public void run() {
				UpdateJob job = new UpdateJob("Search for new extensions", getSearchRequest());
				UpdateManagerUI.openInstaller(window.getShell(), job);
			}
		});
	}
	
	private UpdateSearchRequest getSearchRequest() {
		UpdateSearchRequest result = new UpdateSearchRequest(
				UpdateSearchRequest.createDefaultSiteSearchCategory(),
				new UpdateSearchScope());
		result.addFilter(new BackLevelFilter());
		result.addFilter(new EnvironmentFilter());
		UpdateSearchScope scope = new UpdateSearchScope();
		try {
			String homeBase = System.getProperty("LogViewer.homebase", "file:/c:");
			URL url = new URL(homeBase);
			scope.addSearchSite("LogViewer site", url, null);
		} catch (MalformedURLException e) {
			// skip bad URLs
			e.printStackTrace();
		}
		result.setScope(scope);
		return result;
	}
}
