/*
 *  Draco Econometrics
 *  Copyright (C) 2008-2009 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.approximatrix.draco.application.preferences;

import java.util.Arrays;
import java.util.List;

import javax.swing.SwingUtilities;

import com.approximatrix.draco.application.ApplicationManager;

public class PluginPreferences implements DracoPreferences {
	
	public static String TAG = "plugins";
	
	private String[] directories = null; // We're using an array because it turns out easier for json
	private boolean useParallelMultiply = false;
	private boolean useParallelInverse = false;
	
	private int threadLimit = 1;
	
	public PluginPreferences() {
		directories = new String[0];
	}
	
	public int getThreadLimit() {
		return threadLimit;
	}
	
	public void setThreadLimit(int value) {
		if(value > 0)
			threadLimit = value;
	}
	
	public boolean isParallelMultiplyEnabled() {
		return useParallelMultiply;
	}
	
	public boolean isParallelInverseEnabled() {
		return useParallelInverse;
	}
	
	public void setParallelInverseEnabled(boolean value) {
		useParallelInverse = value;
	}
	
	public void setParallelMultiplyEnabled(boolean value) {
		useParallelMultiply = value;
	}
	
	public final List<String> getDirectories() {
		return Arrays.asList(directories);
	}
	
	public void addDirectory(String directory) {
		if(Arrays.asList(directories).contains(directory))
			return;
		
		String[] newdir = new String[directories.length+1];
		System.arraycopy(directories, 0, newdir, 0, directories.length);
		newdir[newdir.length-1] = directory;
		directories = newdir;
	}
	
	public void removeDirectory(String directory) {
		if(!Arrays.asList(directories).contains(directory))
			return;
		
		String[] newdir = new String[Math.max(directories.length-1,0)];
		int j=0;
		for(int i=0;i<directories.length;i++) {
			if(!directories[i].equals(directory)) {
				newdir[j] = directories[i];
				j++;
			}
		}
		directories = newdir;
	}

	public void apply() {
		new PluginUpdateThread().start();
	}
	
	private class PluginUpdateThread extends Thread {
		public void run() {
			ApplicationManager.GetPluginRegistry().clear();
			ApplicationManager.InitializePlugins();
			ApplicationManager.NotifyNewPlugins();
		}
	}
}
