package monitor.views;


import java.util.Date;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.*;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import org.eclipse.swt.SWT;
import Analysis.ListenerManager;
import Analysis.printer;
//import Analysis.Recover;
import Smells.Smell;


/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class SmellView extends ViewPart implements IPartListener {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "monitor.views.SmellView";//定义字符串
    public static TableViewer smellview;
	public  TableViewer viewer;
	private Action RefactAction;
	private Action action2;
	private Action doubleClickAction;

  public static String EX;
  public static String SG;
  public static String TIME;
	private final class MyColumnLabelProvider extends ColumnLabelProvider {
		@Override
		public String getText(Object element) {
			 Smell aSmell= (Smell) element;
			
			  return aSmell.getText();
		}
	}

	/**
	 * The constructor.
	 */
	public SmellView() {
	//	this.viewer.refresh();
		
		
	}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {              //做了一个表格
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
				| SWT.V_SCROLL | SWT.FULL_SELECTION);//
		smellview=viewer;
		final Table table = viewer.getTable();      //viewer调用getTable函数
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		String[] titles = { "Smell Type", "Exlaination", "Gender", "Married" };
		int[] bounds = { 150, 100, 100, 100 };
		TableViewerColumn col1 = createTableViewerColumn(titles[0], bounds[0],
				0);
		TableViewerColumn col2 = createTableViewerColumn(titles[1], bounds[1],
				1);

		// First column is for the first name

		col1.setLabelProvider(new MyColumnLabelProvider());

		// Second column is for the last name
		col2.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(Object element) {
				Smell aSmell = (Smell) element;
				return aSmell.explaination;
			}
		});
		col2.setEditingSupport(new FirstNameEditingSupport(viewer));
		viewer.setContentProvider(new ArrayContentProvider());
		getSite().setSelectionProvider(viewer);
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(),
				"Monitor.viewer");
		makeActions();
		hookContextMenu();
		contributeToActionBars();
     	ListenerManager listenermanager = new ListenerManager();
		listenermanager.Regid(this.viewer);
		getSite().getWorkbenchWindow().
        getPartService().addPartListener(this);
		hookDoubleClickAction();
		CellEditor[] cellEditors  =   new  CellEditor[ 2 ];
	    cellEditors[ 0 ]  =   null;
	    cellEditors[ 1 ]  =   new  TextCellEditor(viewer.getTable() );
	    viewer.setCellEditors(cellEditors);
	   
	}

		
		
		
	private TableViewerColumn createTableViewerColumn(String title, int bound, final int colNumber) {
		final TableViewerColumn viewerColumn = new TableViewerColumn(viewer,
				SWT.NONE);
		final TableColumn column = viewerColumn.getColumn();
		column.setText(title);
		column.setWidth(bound);
		column.setResizable(true);
		column.setMoveable(true);  
		return viewerColumn;

	}
	private void hookContextMenu() {
        MyActionGroup actionGroup = new MyActionGroup(viewer); 
		actionGroup.fillContextMenu(new MenuManager());
	}	
		
	
	
	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(RefactAction);
		manager.add(new Separator());
		
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(RefactAction);
	
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(RefactAction);
		
	}

	private void makeActions() {
		RefactAction = new Action() {
			public void run() {
		
			ISelection	selection=viewer.getSelection();
			if(selection==null) return;
			Object obj = ((IStructuredSelection)selection).getFirstElement();
		       if (obj==null) return;
			if(obj instanceof Smell)
			{
				Smell asmell= (Smell) obj;
				showMessage(asmell.getText());
				
			}
			}
		};
		RefactAction.setText("Refactor it");
		RefactAction.setToolTipText("Remove it it by refactoring");
		
		RefactAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().
			getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
		
		

	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				if(event.getSelection().isEmpty()) return;
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
		       if (obj==null) return;
		       Smell asmell=(Smell) obj;
		       if(asmell==null) return;
		         EX=null;
		         
		         IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
					IFile file=asmell.getIFile();
					IEditorPart _editor = null;
					try {
						_editor = IDE.openEditor(page, file);
					} catch (PartInitException e) {
						e.printStackTrace();
					}
					if(_editor==null) return;
					CompilationUnitEditor editor=(CompilationUnitEditor)_editor;
					//editor.
				org.eclipse.jface.text.source.ISourceViewer sourceViewer= editor.getViewer();
				//System.out.print("开始位置"+asmell.getStartPoint()+"长度"+asmell.length);
					sourceViewer.setSelectedRange(asmell.getStartPoint(), asmell.getLength());
					sourceViewer.revealRange(asmell.getStartPoint(), asmell.getLength());
		         //noShow no=new noShow();
		         Date date=new Date(asmell.appearTime);
		               
		         TIME=date.toLocaleString();
		       EX=asmell.explaination;
		       SG=asmell.getSuggestion();
		       TheDetail Detail=new TheDetail();
		       
			}
		});
			
		
		
	}

	
	
	
	private  void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Smell View",
			message);
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}

	@Override
	public void partActivated(IWorkbenchPart part) {
		// TODO Auto-generated method stub
		if(part!=this) return;
		//printer.println(" partActivated ");
	}

	@Override
	public void partBroughtToTop(IWorkbenchPart part) {
		// TODO Auto-generated method stub
		if(part!=this) return;
	//	printer.println("!!!partBroughtToTop ");
	}

	
	
	@Override
	public void partClosed(IWorkbenchPart part) {
				// TODO Auto-generated method stub
		if(part!=this) return;
	//	printer.println(" partClosed ") ;
	   
	}

	@Override
	public void partDeactivated(IWorkbenchPart part) {
		// TODO Auto-generated method stub
		if(part!=this) return;
	//	printer.println(" partDeactivated ");
	}

	@Override
	public void partOpened(IWorkbenchPart part) {
		// TODO Auto-generated method stub
		if(part!=this) return;
	//	printer.println(" partOpened ");
	}
}