/*******************************************************************************
 * 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 org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.part.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.graphics.Image;

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

import org.apache.thrift.TException;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.*;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.swt.SWT;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.irtsaintexupery.fiacre.simulator.core.DelayEvent;
import com.irtsaintexupery.fiacre.simulator.core.FiacreSimulator;
import com.irtsaintexupery.fiacre.simulator.core.ReadDelay;
import com.irtsaintexupery.fiacre.simulator.core.Utils;
import com.irtsaintexupery.fiacre.simulator.perspective.ViewsController;
import com.irtsaintexupery.fiacre.simulator.staticjson.extractor.DynamicJsonExtractor;

import fr.laas.libtts.LibTTS;
import tts.Error;
import tts.InvalidDelay;
import tts.StateNotFound;



public class TransitionsView extends ViewPart {

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

	private TableViewer viewer;
	private Action doubleClickAction;
	private Action oneClickAction;
	private Action delay;
	
	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) {
			if (ViewsController.INSTANCE.isFireable(getText(obj))) {
				return PlatformUI.getWorkbench().getSharedImages()
						.getImage(ISharedImages.IMG_OBJ_ADD);
			}else {
				return PlatformUI.getWorkbench().getSharedImages()
						.getImage(ISharedImages.IMG_ELCL_STOP);
			}			
		}
	}
	/**
	 * The constructor.
	 */
	public TransitionsView() {
		// 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(), 
				"TransitionView.viewer");
		getSite().setSelectionProvider(viewer);
		makeActions();
		hookDoubleClickAction();
		hookOneClickAction();
		contributeToActionBars();
		delay.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(delay);		
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(delay);
	}		
		
		
	private void makeActions() {
		
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				//showMessage("Double-click fire on "+obj.toString());
				if (!selection.isEmpty()) {
					if (selection != null && selection instanceof IStructuredSelection 
							&& ViewsController.INSTANCE.isFireable(obj.toString()) 
							) {
						ViewsController.INSTANCE.fireTransition(obj.toString());
					}					
				}
			}
		};
		
		oneClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				if (selection != null & selection instanceof IStructuredSelection 
						&& obj != null) {
					ViewsController.INSTANCE.showSelectedTransition(obj
							.toString());
				}
			}
		};
		
		delay = new Action() {
			public void run() {
				///////////////DELAY
				delay();
			}
		};
		delay.setText("delay");
		delay.setToolTipText("Delay");
		ImageDescriptor imageDescriptordelay = AbstractUIPlugin
				.imageDescriptorFromPlugin( "com.irtsaintexupery.fiacre"
						+ ".simulator", "/icons/time_add.png" );
		
		delay.setImageDescriptor(imageDescriptordelay);
	}
	
	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	
	private void hookOneClickAction() {
		viewer.addSelectionChangedListener(new ISelectionChangedListener() {			
			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				oneClickAction.run();
			}
		});
	}	
       
	private void showMessage(String message) {
		MessageDialog.openInformation(
			viewer.getControl().getShell(),
			"Transition View",
			message);
	}

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

	}

	public void update(ArrayList<String> list) {
		delay.setEnabled(true);
		elementsTable.clear();
		for (String s : list) {
			elementsTable.add(s);			
		}
		viewer.setContentProvider(ArrayContentProvider.getInstance());
		viewer.setInput(elementsTable);
		viewer.setLabelProvider(new ViewLabelProvider());
	}
	
	public void clearContent() {
		elementsTable.clear();
		delay.setEnabled(false);
		viewer.setContentProvider(ArrayContentProvider.getInstance());
		viewer.setInput(elementsTable);
		viewer.setLabelProvider(new ViewLabelProvider());
	}
	
	//Jorge Gutierrez 22/08/2016
	public void delay(){
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getActivePage().getActivePart().getSite().getShell();
		ReadDelay dialog = new ReadDelay(shell);
		dialog.create();
		if (dialog.open() == Window.OK) {
		  dialog.getValue();
			LibTTS libtts = FiacreSimulator.getLibTTS();
			DynamicJsonExtractor dje = FiacreSimulator.sendDje();
			try {
				libtts.getTTSSimulator().delay(dialog.getValue());
				dje.extractExecutableStatements();
						
				
				//Jorge Gutierrez 03/08/2016
				ViewsController.INSTANCE.updateTransitionView();
				ViewsController.INSTANCE.addDelayToAction(dialog.getValue());
				ViewsController.INSTANCE.updateExecutedActionView();
				
				dje.saveInstanceResource();		
			} catch (Error e) {
				// TODO Auto-generated catch block
				Utils.showException("Error",e);
				//e.printStackTrace();
			} catch (StateNotFound e) {
				// TODO Auto-generated catch block
				Utils.showException("StateNotFound",e);
				//e.printStackTrace();
			} catch (InvalidDelay e) {
				// TODO Auto-generated catch block
				Utils.showException("InvalidDelay",e);
				//e.printStackTrace();
			} catch (TException e) {
				// TODO Auto-generated catch block
				Utils.showException("TException",e);
				//e.printStackTrace();
			} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			Utils.showException("NumberFormatException: "+dialog.getValue()+" is not numeric value",e);
			//e.printStackTrace();
		}
		} 
	}
}

