/*
 *  Draco Econometrics
 *  Copyright (C) 2006-2007 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;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.SwingUtilities;

import com.approximatrix.draco.io.GeneralLoadWorksheet;

/** Class to in */
public class InitializeWorker {
	
	private static final long INIT_MS = 1000;
	private static final long SLEEP_MS = 2000;
	
	/** The step, starting at zero, that must always be completed */
	private static final int REQUIRED_TO = 3;
	
	private static final String[] MESSAGES = {"Initializing...",
											  "Loading and Sizing Graphics",
											  "Initializing Scripting Engines",
											  "Loading Plugins",
											  "Creating the Main Window",
											  "Advertising..." };
	
	private List<String> files = null;
	private List<GeneralLoadWorksheet> loaders = null;
	
	public static int GetTotalSteps() {
		return MESSAGES.length;
	}
	
	public InitializeWorker(List<String> files) {
		this.files = files;
		this.loaders = new ArrayList<GeneralLoadWorksheet>();
	}
	
	private boolean hasFiles() {
		if(files == null)
			return false;
		else if(files.size() == 0)
			return false;
		
		return true;
	}
	
	public int getTotalSteps() {
		if(!hasFiles())
			return MESSAGES.length;
		else
			return REQUIRED_TO+2+files.size();
	}
	
	public String getStepDescription(int i) {
		if(i>=0 && i<this.getTotalSteps() && !hasFiles()) 
			return MESSAGES[i];
		else if(i <= REQUIRED_TO)
			return MESSAGES[i];
		else if(i < getTotalSteps()) {
			try {
				return getFileLoading(i-REQUIRED_TO-1);
			} catch(IndexOutOfBoundsException ie) {
				// Expected if a file was not found
				return "Validating...";
			}
		} else
			return "Starting Up...";
	}
	
	private String getFileLoading(int i) throws IndexOutOfBoundsException {
		File f = new File(files.get(i));
		String ret = "Loading " + f.getName();
		if(ret == null) return "Loading file...";
		return ret;
	}
	
	public void doStep(int step) {
		
		if(!hasFiles() || step <= REQUIRED_TO) {
			switch(step) {
				case 0:
					this.advertise(INIT_MS);
					ApplicationManager.SetAutoShutdown(false);
					break;
				case 1:
					this.loadGraphics();
					break;
				case 2:
					ApplicationManager.InitializeScripting();
					break;
				case 3:
					ApplicationManager.InitializePlugins();
					break;
				case 4:
					this.createMainWindow();
					break;
				case 5:
					this.advertise(SLEEP_MS);
					ApplicationManager.SetAutoShutdown(true);
					break;
			}
		} else {
			try {
				this.loadFile(step-REQUIRED_TO-1);
			} catch(IndexOutOfBoundsException ie) {
				// Expected if we're past the file list
				this.checkAndFixWindows();
			}
			
		}
	}
	
	private void loadGraphics() {
		ApplicationManager.LoadIcons();
	}
	
	private void checkAndFixWindows() {
		boolean wait = true;
		while(wait) {
			wait = false;
			for(GeneralLoadWorksheet loader : loaders) {
				if(loader.isLoading()) {
					wait = true;
					break;
				}
			}
			
			try {
				Thread.sleep(500);
			} catch(InterruptedException ie) {
				System.err.println("Interrupted while waiting for file loading to complete...");
				break;
			}
		}
		
		Runnable doValidateOrCreateWindow = new Runnable() {
            public void run() {
            	if(ApplicationManager.RequestWindowCount() == 0)
            		ApplicationManager.RequestNewWindow();
            	ApplicationManager.SetAutoShutdown(true);
            }
        };
		SwingUtilities.invokeLater(doValidateOrCreateWindow);
	}
	
	private void createMainWindow() {
		Runnable doCreateWindow = new Runnable() {
            public void run() {
            	ApplicationManager.RequestNewWindow();
            }
        };
		SwingUtilities.invokeLater(doCreateWindow);
	}
	
	private void loadFile(int i) throws IndexOutOfBoundsException {
		String toLoad = files.get(i);
		GeneralLoadWorksheet loader = new GeneralLoadWorksheet(toLoad);
		loaders.add(loader);
		final GeneralLoadWorksheet passableLoader = loader;
		
		Runnable doLoadFile = new Runnable() {
            public void run() {
            	passableLoader.load();
            }
        };
		SwingUtilities.invokeLater(doLoadFile);
	}
	
	private void advertise(final long ms) {
		try {
			Thread.sleep(ms);
		} catch (InterruptedException ie) {
			System.err.println("Problem advertising...");
		}
	}
	
}



