/**
 * File:    RecentFilesList.java
 * Created: 10.10.2006
 *
 *
/*******************************************************************************
 * Copyright (c) 2005-2011
 * University of Augsburg, Germany <www.ds-lab.org>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Wolf Fischer, Programming distributed Systems Lab, University of Augsburg 
 *    	- initial API and implementation
 *******************************************************************************/

package org.eclipse.jwt.we.editors.actions.managed.recentfiles;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jwt.we.Plugin;
import org.eclipse.jwt.we.editors.actions.internal.WEAbstractMenuManager;
import org.eclipse.jwt.we.misc.logging.Logger;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.osgi.framework.Bundle;


/**
 * Manages the recently used files list and stores them in the Eclipse Preferences
 * 
 * @version $Id: RecentFilesListManager.java,v 1.12 2009-11-26 12:41:48 chsaad Exp $
 * @author Wolf Fischer, Programming distributed Systems Lab, University of Augsburg,
 *         Germany, www.ds-lab.org
 */
public class RecentFilesListManager
		extends WEAbstractMenuManager
{

	/**
	 * A logger.
	 */
	private static Logger logger = Logger.getLogger(RecentFilesListManager.class);

	private static final String PREFERENCE_PREFIX = "recentfile";  //$NON-NLS-1$
	private static final int NUMBER_OF_FILES = 10;
	private static final String CONFIG_FILENAME = "recentfiles.dat";  //$NON-NLS-1$
	private List<RecentFileAction> fileactionlist = new ArrayList<RecentFileAction>(
			NUMBER_OF_FILES);

	/**
	 * The singleton instance.
	 */
	private static RecentFilesListManager myinstance;


	/**
	 * Standardconstructor
	 * 
	 */
	private RecentFilesListManager()
	{
		load();
	}


	/**
	 * Returns a value identification
	 * 
	 * @param id
	 * @return
	 */
	public static String getName(int id)
	{
		return PREFERENCE_PREFIX + id;
	}


	/**
	 * Returns an instance to this manager
	 * 
	 * @return
	 */
	public static RecentFilesListManager getInstance()
	{
		if (myinstance == null)
			myinstance = new RecentFilesListManager();
		return myinstance;
	}


	/**
	 * Simply fills the given menu
	 * 
	 */
	public void fillMenuInitial()
	{
		try
		{
			menu.removeAll();
			if (fileactionlist.size() <= 0)
			{
				addToMenuAndRegister(new RecentFileAction("", ""));  //$NON-NLS-1$  //$NON-NLS-2$
				return;
			}
			for (int i = fileactionlist.size() - 1; i >= 0; i--)
			{
				addToMenuAndRegister(fileactionlist.get(i));
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}


	/**
	 * Adds / sets a new file
	 * 
	 * @param file
	 *            The name of the file
	 */
	public void setNewFile(String file)
	{
		try
		{
			/**
			 * permits the list from adding the same file more often than once
			 */
			for (int i = 0; i < fileactionlist.size(); i++)
			{
				if (fileactionlist.get(i).getFilename().equals(
						RecentFileAction.makeFilename(file)))
					return;
			}
			String id = "";  //$NON-NLS-1$
			if (fileactionlist.size() >= NUMBER_OF_FILES)
			{
				RecentFileAction rfa = fileactionlist.get(0);
				fileactionlist.remove(rfa);
			}
			id = PREFERENCE_PREFIX + fileactionlist.size();
			fileactionlist.add(new RecentFileAction(file, id));
			save();
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}


	/**
	 * Saves the parameter in a file on the hdd
	 */
	private void save()
	{
		try
		{

			File configfile = getFileHandle(CONFIG_FILENAME);

			if (configfile == null)
				return;
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
					configfile));
			oos.writeObject(fileactionlist);
			oos.flush();
			oos.close();
		}
		catch (Exception ex)
		{
			logger.info(ex.toString());
		}
	}


	/**
	 * Loads the parameter from a file on the hdd
	 */
	private void load()
	{
		try
		{
			File configfile = getFileHandle(CONFIG_FILENAME);
			if (configfile == null || !configfile.exists())
				return;
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(configfile));
			fileactionlist = (List<RecentFileAction>) ois.readObject();
			ois.close();
			for (int i = 0; i < fileactionlist.size(); i++)
			{
				RecentFileAction rfa = fileactionlist.get(i);
				fileactionlist.get(i).setText(rfa.getFilename());
				fileactionlist.get(i).setId(getName(i));
			}

			List<RecentFileAction> newlist = new ArrayList<RecentFileAction>();
			for (RecentFileAction rfa : fileactionlist)
			{
				// File f = new File(rfa.getFilename().replace("file:/", ""));
				// if (f.exists())
				newlist.add(rfa);
			}
			fileactionlist = newlist;
			save();
		}
		catch (Exception ex)
		{
			logger.info(ex.toString());
		}
	}


	/**
	 * Returns a filehandle to the config file
	 * 
	 * @return {@link File}
	 */
	public static File getFileHandle(String filetohandle)
	{
		try
		{
			Plugin defaultplugin = Plugin.getDefault();
			File viewdir = null;
			URL viewsfullpath = null;
			if (defaultplugin != null)
			{
				Bundle bundle = defaultplugin.getBundle();
				URL viewspath = bundle.getEntry("");  //$NON-NLS-1$

				if (viewspath != null)
				{
					viewsfullpath = FileLocator.resolve(viewspath);
				}

				File testfile = new File(viewsfullpath.getPath());
				if (testfile == null || testfile.isFile()
						|| testfile.getAbsolutePath().endsWith("!"))  //$NON-NLS-1$
				{
					viewdir = null;
				}
				else
					viewdir = new File(viewsfullpath.getPath() + "/" + filetohandle);  //$NON-NLS-1$

			}
			if (viewdir == null)
			{
				File currentpathfile = new File(".");  //$NON-NLS-1$

				String currentpath = currentpathfile.getAbsolutePath();
				currentpath = currentpath.substring(0, currentpath.length() - 2);
				viewdir = new File(currentpath + "\\" + filetohandle);  //$NON-NLS-1$
			}
			return viewdir;
		}
		catch (Exception ex)
		{

		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jwt.we.editors.actions.internal.WEAbstractMenuManager#setActionBarConfigurer(org.eclipse.ui.application.IActionBarConfigurer)
	 */
	@Override
	public void setActionBarConfigurer(IActionBarConfigurer acbar)
	{
		super.setActionBarConfigurer(acbar);
	}


	/* (non-Javadoc)
	 * @see org.eclipse.jwt.we.editors.actions.internal.WEAbstractMenuManager#setMenu(org.eclipse.jface.action.IMenuManager)
	 */
	@Override
	public void setMenu(IMenuManager menu)
	{
		super.setMenu(menu);
	}


	/* (non-Javadoc)
	 * @see org.eclipse.jwt.we.editors.actions.internal.WEAbstractMenuManager#setWindowHandle(org.eclipse.ui.IWorkbenchWindow)
	 */
	@Override
	public void setWindowHandle(IWorkbenchWindow window)
	{
		super.setWindowHandle(window);
	}

}
