package net.kldp.logviewer;

import net.kldp.logviewer.common.log.LogViews;
import net.kldp.logviewer.model.LogViewerEntry;
import net.kldp.logviewer.model.LogViewerGroup;

import org.apache.log4j.Logger;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

/**
 * 정의된 로그의 전체 로그를 보여준다.
 * 
 * @author hangum
 */
public class AllLogViewAction extends Action implements ISelectionListener, IWorkbenchAction {

	private static final Logger logger = LogViews.getLogger(AllLogViewAction.class);
	
	private final IWorkbenchWindow window;
	public final static String ID = "net.kldp.logviewer.AllLogView";
	private IStructuredSelection selection;
	LogViewerEntry entry = new LogViewerEntry();
	private final String viewId;
	
    public AllLogViewAction(IWorkbenchWindow window, String label, String viewId) {    	
        super(label);
        
        this.viewId = viewId;
        this.window = window;
        // The id is used to refer to the action in a menu or toolbar
        setId(ICommandIds.CMD_OPEN_MESSAGE);
        // Associate the action with a pre-defined command, to allow key bindings.
        setActionDefinitionId(ICommandIds.CMD_OPEN_MESSAGE);
        setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, IImageKeys.LOG));
        
        window.getSelectionService().addSelectionListener(this);
    }

    public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}

	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
		
		if (incoming instanceof IStructuredSelection) {
			selection = (IStructuredSelection) incoming;			
			
			// 그룹 선택시 신규이다.
			if(selection.size() == 1 &&  selection.getFirstElement() instanceof LogViewerEntry) {
				setEnabled(true);
			} else {
				setEnabled(false);
			}
		
		} else {
			// Other selections, for example containing text or of other kinds.
			setEnabled(false);
		}
	}

	public void run() {
		LogViewerEntry entry = (LogViewerEntry) selection.getFirstElement();
		
		if(window != null) {
			try {				
				logger.debug("[viewId]"+ viewId);
				
				window.getActivePage().showView(viewId, ""+entry.getSeq(), IWorkbenchPage.VIEW_ACTIVATE);
			} catch (PartInitException e) {
				MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e.getMessage());
			}
		}
	}	
}