/*******************************************************************************
 * Copyright (c) 2015, 2016 CNRS, IRIT, IRT AESE (IRT Saint Exupéry).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the LGPL 3.0
 * which accompanies this distribution, and is available at
 * https://www.gnu.org/licenses/lgpl-3.0-standalone.html
 *
 * Contributors:
 *     Faiez Zalila - initial API and implementation and/or initial documentation
 *     Jorge Enrique Gutierrez Zuluaga
 *******************************************************************************/
package com.irtsaintexupery.fiacre.simulator.perspective.views;

import java.util.ArrayList;
import java.util.Vector;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.irtsaintexupery.fiacre.simulator.perspective.ViewsController;
import com.irtsaintexupery.fiacre.simulator.perspective.views.ExecutedActionView.ViewLabelProvider;

public class SavedStatesView extends ViewPart {

	public static final String ID = "com.irtsaintexupery.fiacre.simulator"
			+ ".perspective.SavedStatesView";

	private TableViewer viewer;
	private Action save;
	private Action goTo;
	private Action delete;
	
	private Vector <String> elementsTable = new Vector <String> ();
	
	class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			return getText(obj);
		}
		public Image getColumnImage(Object obj, int index) {
			return getImage(obj);
		}
		public Image getImage(Object obj) {
			return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages
					.IMG_OPEN_MARKER);
			
		}
	}
	/**
	 * The constructor.
	 */
	public SavedStatesView() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		
		viewer.setContentProvider(ArrayContentProvider.getInstance());
		//TODO add elements to the table
		viewer.setInput(elementsTable);
		viewer.setLabelProvider(new ViewLabelProvider());

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), 
				"ExecutedActionView.viewer");
		getSite().setSelectionProvider(viewer);
		makeActions();
		contributeToActionBars();
		save.setEnabled(false);
		goTo.setEnabled(false);
		delete.setEnabled(false);

	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(new Separator());
		manager.add(save);
		manager.add(new Separator());
		manager.add(goTo);
		manager.add(new Separator());
		manager.add(delete);
		
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(save);
		manager.add(goTo);
		manager.add(delete);
	}
	
	private void makeActions() {
		
		save = new Action() {
			public void run() {
				SaveStateDialog dialog = new SaveStateDialog(viewer.getControl().getShell());
				dialog.create();
				if (dialog.open() == Window.OK) {
					  elementsTable.add(dialog.getTag());
					  ViewsController.INSTANCE.addStateToMap(dialog.getTag());
				}
			}
		};
		save.setText("Save");
		save.setToolTipText("Save");
		ImageDescriptor imageDescriptorSave = AbstractUIPlugin
				.imageDescriptorFromPlugin( "com.irtsaintexupery.fiacre"
						+ ".simulator", "/icons/brick_add.png" );		
		save.setImageDescriptor(imageDescriptorSave);
		
		goTo = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
                Object obj = ((IStructuredSelection)selection).getFirstElement();
                if (!selection.isEmpty()) {
                    if (selection != null && selection instanceof IStructuredSelection) {
                        ViewsController.INSTANCE.goToState(obj.toString());
                    }
			}
           }
		};
		goTo.setText("GoTo");
		goTo.setToolTipText("GoTo");
		ImageDescriptor imageDescriptorGoTo = AbstractUIPlugin
				.imageDescriptorFromPlugin( "com.irtsaintexupery.fiacre"
						+ ".simulator", "/icons/brick_go.png" );		
		goTo.setImageDescriptor(imageDescriptorGoTo);
		
		delete = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				if (!selection.isEmpty()) {
					if (selection != null && selection instanceof IStructuredSelection) {
						ViewsController.INSTANCE.deleteState(obj.toString());
					}					
				}
			}
		};
		delete.setText("Delete");
		delete.setToolTipText("Delete");
		ImageDescriptor imageDescriptorDelete = AbstractUIPlugin
				.imageDescriptorFromPlugin( "com.irtsaintexupery.fiacre"
						+ ".simulator", "/icons/brick_delete.png" );		
		delete.setImageDescriptor(imageDescriptorDelete);
		
	}
	
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Executed Action View",
			message);
	}

	@Override
	public void setFocus() {
		viewer.getControl().setFocus();

	}
	
	
	public class SaveStateDialog extends TitleAreaDialog {
		private Text tagLabel;
		private String tag;
		
		public SaveStateDialog(Shell parentShell) {
			super(parentShell);
			// TODO Auto-generated constructor stub
		}		
		
		@Override
		  public void create() {
		    super.create();
		    setTitle("Save state");
		    setMessage("write a identifier Tag to current state", IMessageProvider.INFORMATION);
		  }

		  @Override
		  protected Control createDialogArea(Composite parent) {
		    Composite area = (Composite) super.createDialogArea(parent);
		    Composite container = new Composite(area, SWT.NONE);
		    container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		    GridLayout layout = new GridLayout(2, false);
		    container.setLayout(layout);

		    createTagLabel(container);

		    return area;
		  }

		  private void createTagLabel(Composite container) {
		    Label lbtFirstName = new Label(container, SWT.NONE);
		    lbtFirstName.setText("State Tag");

		    GridData dataFirstName = new GridData();
		    dataFirstName.grabExcessHorizontalSpace = true;
		    dataFirstName.horizontalAlignment = GridData.FILL;

		    tagLabel = new Text(container, SWT.BORDER);
		    tagLabel.setLayoutData(dataFirstName);
		  }


		  @Override
		  protected boolean isResizable() {
		    return true;
		  }

		  // save content of the Text fields because they get disposed
		  // as soon as the Dialog closes
		  private void saveInput() {
		    tag = tagLabel.getText();

		  }

		  @Override
		  protected void okPressed() {
		    saveInput();
		    super.okPressed();
		  }

		  public String getTag() {
		    return tag;
		  }		  
	}
	
	public void update(ArrayList<String> list) {
		elementsTable.clear();
		for (String s : list) {
			elementsTable.add(s);
		}
		if(ViewsController.INSTANCE.getFile() != null){
			save.setEnabled(true);
			goTo.setEnabled(true);
			delete.setEnabled(true);
		}else {
			save.setEnabled(false);
			goTo.setEnabled(false);
			delete.setEnabled(false);
		}
		viewer.setContentProvider(ArrayContentProvider.getInstance());
		viewer.setInput(elementsTable);
		viewer.setLabelProvider(new ViewLabelProvider());
	}

}