/* 
-*- coding: latin-1 -*-

This file is part of RefactorErl.

RefactorErl is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

RefactorErl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with RefactorErl.  If not, see <http://plc.inf.elte.hu/erlang/>.

The Original Code is RefactorErl.

The Initial Developer of the Original Code is Eötvös Loránd University.
Portions created  by Eötvös Loránd University and ELTE-Soft Ltd.
are Copyright 2007-2025 Eötvös Loránd University, ELTE-Soft Ltd.
and Ericsson Hungary. All Rights Reserved.
 */

package com.refactorerl.ui.presentation.dupcode;

import java.util.List;

import org.eclipse.core.resources.IStorage;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditor;

import com.refactorerl.ui.common.FilePosition;
import com.refactorerl.ui.logic.dupcode.CloneData;
import com.refactorerl.ui.logic.dupcode.GroupData;
import com.refactorerl.ui.presentation.Activator;
import com.refactorerl.ui.presentation.codebrowser.StringInput;
import com.refactorerl.ui.presentation.codebrowser.StringStorage;

/**
 * Defines the composite holding the JFace TableViewer which hosts the list of
 * results of the duplicated code analysis.
 * 
 * @author Daniel Lukacs, 2014 ELTE IK
 *
 */
public class ClonesResultView extends ViewPart {

	private CloneData input;
	private TableViewer tv;

	private Button outputButton;
	private Form form;

	public void setInput(CloneData input) {
		this.input = input;
		form.setText(Messages.ClonesResultView_0 + input.getName());
		outputButton.setEnabled(input.getOutputPath() != null);
		createTableViewer(tv.getTable().getParent());
		tv.setInput(input.getDuplicates());
		// createColumns(tv);
	}

	@Override
	public void createPartControl(Composite parent) {
		FormToolkit toolkit = new FormToolkit(parent.getDisplay());
		form = toolkit.createForm(parent);
		form.setText(Messages.ClonesResultView_1);
		toolkit.decorateFormHeading(form);

		Composite headClient = toolkit.createComposite(form.getHead());
		form.setHeadClient(headClient);
		headClient.setLayout(new RowLayout(SWT.VERTICAL));
		toolkit.createLabel(headClient, Messages.ClonesResultView_2);
		outputButton = toolkit.createButton(headClient,
				Messages.ClonesResultView_3, SWT.PUSH);
		outputButton.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				openOutputFile(input.getOutputPath());
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// not called
			}
		});

		form.getBody().setLayout(new GridLayout(1, false));

		// Create the composite
		Composite composite = new Composite(form.getBody(), SWT.NONE);
		composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));

		createTableViewer(composite);

	}

	@Override
	public void setFocus() {
	}

	private void createTableViewer(Composite parent) {
		Composite cmp = parent;
		if (tv == null) {
			tv = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION);
		} else {
			Table table = tv.getTable();
			cmp = table.getParent();
			table.dispose();
			tv = new TableViewer(cmp);
		}
		tv.setUseHashlookup(true);

		tv.getTable().setLinesVisible(true);
		tv.getTable().setHeaderVisible(true);
		
		createColumns(tv);
		
		tv.setContentProvider(new IStructuredContentProvider() {
			private List<GroupData> input;

			@Override
			public void inputChanged(Viewer viewer, Object oldInput,
					Object newInput) {
				this.input = (List<GroupData>) newInput;

			}

			@Override
			public void dispose() {
			}

			@Override
			public Object[] getElements(Object inputElement) {

				return input.toArray();
			}
		});

		tv.setLabelProvider(new ITableLabelProvider() {

			@Override
			public void removeListener(ILabelProviderListener listener) {

			}

			@Override
			public boolean isLabelProperty(Object element, String property) {

				return false;
			}

			@Override
			public void dispose() {

			}

			@Override
			public void addListener(ILabelProviderListener listener) {

			}

			@Override
			public String getColumnText(Object element, int columnIndex) {
				GroupData row = (GroupData) element;
				if (columnIndex == 0) {
					return Integer.toString(row.getMembers().size());
				} else if (columnIndex - 1 < row.getMembers().size()) {
					return row.getMembers().get(columnIndex - 1).toString();
				}
				return ""; //$NON-NLS-1$
			}

			@Override
			public Image getColumnImage(Object element, int columnIndex) {

				return null;
			}
		});
		tv.addDoubleClickListener(new IDoubleClickListener() {

			@Override
			public void doubleClick(DoubleClickEvent event) {

				GroupData group = (GroupData) ((IStructuredSelection) event
						.getSelection()).getFirstElement();
				final Shell shell = getSite().getShell();
				DupCodeHelper.openEditor(group, shell);
			}

		});
		MenuManager menuManager = new MenuManager();
		Menu menu = menuManager.createContextMenu(tv.getControl());

		tv.getControl().setMenu(menu);
		getSite().registerContextMenu(menuManager, tv);
		getSite().setSelectionProvider(tv);

		cmp.layout(true);
	}

	private void createColumns(TableViewer tableViewer) {
		TableColumnLayout layout = new TableColumnLayout();
		tableViewer.getTable().getParent().setLayout(layout);

		TableViewerColumn groupSizeTVC = new TableViewerColumn(tableViewer,
				SWT.NONE);
		TableColumn groupSizeTC = groupSizeTVC.getColumn();
		layout.setColumnData(groupSizeTC, new ColumnWeightData(0,
				ColumnWeightData.MINIMUM_WIDTH, true));

		if (input != null) {
			int maxGroupSize = 0;
			for (GroupData group : input.getDuplicates()) {
				int n = group.getMembers().size();
				maxGroupSize = n > maxGroupSize ? n : maxGroupSize;
			}

			for (int i = 0; i < maxGroupSize; i++) {
				TableViewerColumn tvc = new TableViewerColumn(tableViewer,
						SWT.NONE);
				TableColumn tc = tvc.getColumn();
				layout.setColumnData(tc, new ColumnWeightData(2,
						ColumnWeightData.MINIMUM_WIDTH, true));
				tc.setResizable(true);				
			}

		}

	}

	private void openOutputFile(final String outputPath) {
		if (outputPath == null)
			return;
		IStorage storage = new StringStorage(outputPath);
		IStorageEditorInput input = new StringInput(storage);

		ITextEditor ed;
		try {
			ed = (ITextEditor) getSite().getWorkbenchWindow().getActivePage()
					.openEditor(input, "org.eclipse.ui.DefaultTextEditor"); //$NON-NLS-1$

		} catch (PartInitException e1) {
			Activator.showErrorDialog(e1, getSite().getShell());
		}
	}

	public String getName() {
		return input.getName();
	}

	public GroupData getSelection() {
		return (GroupData) ((IStructuredSelection) tv.getSelection())
				.getFirstElement();
	}

	public void removeGroup(GroupData group) {
		tv.remove(group);
	}

	public CloneData getInput() {
		return input;
	}
}
