package net.kldp.logviewer;

import net.kldp.logviewer.common.log.LogViews;
import net.kldp.logviewer.model.GetLogDBInfo;
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.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

/**
 * 로그정보를 삭제한다.
 * 
 * @author hangum
 *
 */
public class DelLogAction extends Action implements ISelectionListener, IWorkbenchAction {

	private static final Logger logger = LogViews.getLogger(DelLogAction.class);
	
	private final IWorkbenchWindow window;
	public final static String ID = "net.kldp.logviewer.DelLog";
	private IStructuredSelection selection;
	
	
	//LogViewerEntry entry = new LogViewerEntry();
	
    public DelLogAction(IWorkbenchWindow window, String label) {    	
        super(label);
        
    	logger.debug("[DelAction] called....");
    	
        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_DEL));
        
        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();
		
		boolean boolYN = MessageDialog.openQuestion(window.getShell(), "확인", entry.getName() + "을 삭제 하시겠습니까?");
		if(boolYN) {			
			GetLogDBInfo info = new GetLogDBInfo();
			info.delLog(entry.getSeq());
			
			// tree에서 항목을 삭제한다.
			LogViewerGroup group = entry.getParent();
			group.removeEntry(entry);
		}
	}	
}