package es.uma.lcc.ama.maudeWorkstationGUI.core;

import java.util.StringTokenizer;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.Workbench;

import es.uma.lcc.ama.maudeWorkstationGUI.MaudeWorkstationGUIPlugin;
import es.uma.lcc.ama.maudeWorkstationGUI.Messages;
import es.uma.lcc.ama.maudeWorkstationGUI.core.database.MaudeDataBase;
import es.uma.lcc.ama.maudeWorkstationGUI.ui.states.MaudeSesion;
import es.uma.lcc.ama.maudeWorkstationGUI.ui.views.MaudeDepuracion;
import es.uma.lcc.ama.maudeWorkstationGUI.ui.views.MaudeRewriting;
import es.uma.lcc.ama.maudeWorkstationGUI.ui.views.MaudeTraza;
import es.uma.lcc.ama.maudedaemon.core.MaudeDaemonPlugin;
import es.uma.lcc.ama.maudedaemon.ui.preferences.PreferenceConstants;
import es.uma.lcc.ama.maudesimpleGUI.MaudesimpleGUIPlugin;
import es.uma.lcc.ama.maudesimpleGUI.core.Maude;

/**
 * Thread that refresh the state of Maude environ.
 * 
 * @author Alfredo
 *
 */
public class MaudeThreadState extends Thread {
	private int time;
	private Thread me;
	private boolean isRunningMaude,isDebuging;
	
	/**
	 * The constructor of this thread. The default refresh rate is 500ms.
	 * 
	 * @param name The name of the thread
	 */
	public MaudeThreadState(String name){
		this(name,500);
	}
	
	/**
	 * The constructor of this thread.
	 * 
	 * @param name The name of the thread
	 * @param t The time of the refresh
	 */
	public MaudeThreadState(String name,int t){
		super(name);
		time=t;
		me=this;
		isRunningMaude=false;
		isDebuging=false;
	}
	
	public void run(){
		while(Thread.currentThread()== me){
				
			    Maude mp=MaudesimpleGUIPlugin.getDefault().getMaude();
				if(mp!=null && isRunningMaude!=mp.isRunning()){
					isRunningMaude=MaudesimpleGUIPlugin.getDefault().isStarted(); //.getMaude().isRunning();
					if(isRunningMaude){
						/*while(!MaudesimpleGUIPlugin.getDefault().isStarted()){
							try {
								Thread.sleep(50);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}	
						}*/

						enableComponents();
					}
					else disableComponents();
				}
				
				if(isDebuging!=MaudesimpleGUIPlugin.getDefault().isDebuging()){
					isDebuging=MaudesimpleGUIPlugin.getDefault().isDebuging();
				    setDebuging(isDebuging);
				}
				
				//if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println("Hebra.. "+this.getName());
			try {
				Thread.sleep(time);
			} catch (Exception e) {}
		
		}
		
	}
	
	/**
	 *  Forces the thread to stop executing.
	 * 
	 */
	public void stopThread(){
		me=null;
		if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println("Hebra parada"); //$NON-NLS-1$
	}
	
	
	
	/**
	 * @param path
	 *            Path in Windows format
	 * @return Path in Unix format
	 */

	private String getPathCygwin(String path) {
		String result = "/cygdrive/" + path.charAt(0) +"/";
		StringTokenizer stok = new StringTokenizer(path, "\\");
		stok.nextToken();
		while (stok.hasMoreTokens()) {
			result += stok.nextToken() + "/";

		}

		result = result.substring(0, result.length() - 1);
		return result;

	}
	
	
	/**
	 * Enables the trace and debug components and reset it
	 */
	private void enableComponents(){
		if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println("Habilitando componentes...."); //$NON-NLS-1$
		
		String rutaCig=ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString();
		if(System.getProperty("os.name").equals("Windows 95") ||
				System.getProperty("os.name").startsWith("Windows"))
			rutaCig=getPathCygwin(ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString());
		
		final String rutaCig2=rutaCig;
		
		//cuidado que esto no es thread safe ya que tenemos que encolarlo en la cola.
		Workbench.getInstance().getDisplay().syncExec(new Runnable() {
			public void run() {
				 
				if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println("Creando una nueva sesion...."); //$NON-NLS-1$
			    MaudeSesion.newInstance().reset();
			    
			    MaudeTraza traza = (MaudeTraza) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(Messages.getString("MaudeWorkstationGUIPlugin.MAUDE_TRAZA"));  //$NON-NLS-1$
				if(traza!=null) traza.reset();
			    MaudeDepuracion debug = (MaudeDepuracion) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(Messages.getString("MaudeWorkstationGUIPlugin.MAUDE_DEPURACION"));  //$NON-NLS-1$
				if(debug!=null) debug.reset();
			    MaudeRewriting rewriting = (MaudeRewriting) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(Messages.getString("MaudeWorkstationGUIPlugin.MAUDE_REWRITING")); //$NON-NLS-1$
			    
				if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println("Habilitando base de datos...."); //$NON-NLS-1$
				
				//setPathDatabase();
				
				if(MaudeWorkstationGUIPlugin.getDefault().getMaudeProcess().isCoreMaude()){
					MaudeWorkstationGUIPlugin.getDefault().setEnabledDatabase(MaudeWorkstationGUIPlugin.getDefault().getDatabase().initCoreMaudeDatabase());	
				}
				else{
					MaudeWorkstationGUIPlugin.getDefault().setEnabledDatabase(MaudeWorkstationGUIPlugin.getDefault().getDatabase().initFullMaudeDatabase());	
				}
				if(rewriting!=null) rewriting.reset();
				
			/*	if(!MaudeWorkstationGUIPlugin.getDefault().isEnabledDatabase()){
					createTasksDatabase();
				} */
			}
		});
		
		
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(MaudeDaemonPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_SERVEROFF))
		//cuidado que esto no es thread safe ya que tenemos que encolarlo en la cola.
		Workbench.getInstance().getDisplay().syncExec(new Runnable() {
			public void run() {
				MaudeWorkstationGUIPlugin.getDefault().sendToMaude("cd "+rutaCig2);
			}});
	}
	
	/*private void setPathDatabase(){
	   	final IPreferenceStore store = MaudeDaemonPlugin.getDefault()
		.getPreferenceStore();
    	
	   	
	   	final String pathDatabase=store.getString(PreferenceConstants.P_PATHLOG);
	   	
	   	String space= System.getProperty("file.separator");
	   	
    	final String pathCoreMaude= pathDatabase+space+"coreMaude.db";
    	if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println(Messages.getString("MaudeWorkstationGUIPlugin.PREFERENCE_PATH_CORE")+pathCoreMaude); //$NON-NLS-1$
    	
      	final String pathFullMaude= pathDatabase+space+"fullMaude.db";
    	if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println(Messages.getString("MaudeWorkstationGUIPlugin.PREFERENCE_PATH_FULL")+pathFullMaude); //$NON-NLS-1$
    
        
        MaudeDataBase.newInstance().setPathCoreMaude(pathCoreMaude);
        MaudeDataBase.newInstance().setPathFullMaude(pathFullMaude);
		
	}*/
	
	
	/*
	
	private void createTasksDatabase(){
	   	final IPreferenceStore store = MaudeDaemonPlugin.getDefault()
		.getPreferenceStore();
               
	        if(MessageDialog.openQuestion(
	    			null,
	    			Messages.getString("MaudeWorkstationGUIPlugin.NOTICE"), //$NON-NLS-1$
	    			Messages.getString("MaudeWorkstationGUIPlugin.CREATE_MAUDE_DATABASE"))){ //$NON-NLS-1$
	        	
	           Job job = new Job(Messages.getString("MaudeWorkstationGUIPlugin.CREATING_MAUDE_DATABASE")) { //$NON-NLS-1$
	        		 @Override
	        	     protected IStatus run(IProgressMonitor monitor) {
	        			   IStatus estado= Status.OK_STATUS;
	        			   
	        	           if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println("Maude database job (from a background job)"); //$NON-NLS-1$
	        	           this.setName(Messages.getString("MaudeWorkstationGUIPlugin.CREATING_CORE_MAUDE_DATABASE")); //$NON-NLS-1$
	        	           estado=MaudeDataBase.newInstance().createsCoreMaudeDatabase(store.getString(PreferenceConstants.P_PATHPRELUDE),monitor);
	        	           if(!store.getString(PreferenceConstants.P_PATHFM).equals("")){ //$NON-NLS-1$
	        	        	   this.setName(Messages.getString("MaudeWorkstationGUIPlugin.CREATING_FULL_MAUDE_DATABASE")); //$NON-NLS-1$
	        	        	   estado=MaudeDataBase.newInstance().createsFullMaudeDatabase(store.getString(PreferenceConstants.P_PATHFM),monitor);
	        	           }
	        	            
	        	           return estado;
	        	        }
	
	        	     };
	        	  job.setPriority(Job.INTERACTIVE);
	        	 // job.setSystem(true);

	        	  job.schedule(); // start as soon as possible
	        }
	        	  
	       

	}
	
	*/
	
	private void disableComponents(){
		if(MaudeWorkstationGUIPlugin.DEBUG) System.out.println("Deshabilitando componentes...."); //$NON-NLS-1$
		//Borro la base de datos
		MaudeWorkstationGUIPlugin.getDefault().getDatabase().borrarBaseDatos();
		//Desabilito el estado de la base de datos
		MaudeWorkstationGUIPlugin.getDefault().setEnabledDatabase(false);
		//desactivo el panel de traza
	}
	
	
	private void setDebuging(final boolean state){
	    Workbench.getInstance().getDisplay().syncExec(new Runnable() {
			public void run() {
					MaudeDepuracion depuracion = (MaudeDepuracion) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(Messages.getString("MaudeWorkstationGUIPlugin.MAUDE_DEPURACION")); //$NON-NLS-1$
						if(depuracion==null){
							try {
								PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(Messages.getString("MaudeWorkstationGUIPlugin.MAUDE_DEPURACION")); //$NON-NLS-1$
							} catch (PartInitException e) {
								e.printStackTrace();
							}
							depuracion = (MaudeDepuracion) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(Messages.getString("MaudeWorkstationGUIPlugin.MAUDE_DEPURACION")); //$NON-NLS-1$
							
						}
						else{
							try {
								PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(Messages.getString("MaudeWorkstationGUIPlugin.MAUDE_DEPURACION")); //$NON-NLS-1$
							} catch (PartInitException e) {
								e.printStackTrace();
							}
						}
						if(state)depuracion.enable();
						else depuracion.disable();
											
			}});
	}
	
	

}
