/*
 *  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.io;

import java.io.File;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;


import com.approximatrix.draco.application.ApplicationManager;
import com.approximatrix.draco.main.ui.MainWindow;
import com.approximatrix.draco.main.ui.WorksheetHandler;
import com.approximatrix.draco.datamodel.StatTableModel;
import com.approximatrix.draco.io.XMLio.LoadWorksheet;
import com.approximatrix.draco.io.sql.DracoSQLRead;
import com.approximatrix.draco.io.sql.DracoSQLWrite;
import com.approximatrix.draco.io.ui.IOFileWorkerDialog;
import com.approximatrix.draco.io.ui.IOWorker;

public class LoadDracoSQL implements IOWorker, DracoLoader {

	private static final String LOAD_WORKSHEET_TITLE = "Loading "+ApplicationManager.APP_NAME+" File...";
	private static final String[] LOAD_STEPS = {"Initializing SQL Connection",
												"Loading Data",
												"Retrieving Constants",
												"Rebuilding Analyses",
												"Rebuilding Regressions",
												"Generating Plots and Charts",
												"Loading Texts",
												"Loading Plugins",
												"Closing Document"};
	private static final int TOTAL_STEPS = 9;
	
	private int current_step = 0;
	private String filename = null;
	private WorksheetHandler parent = null;
	
	private DracoSQLRead sql = null;
	private boolean success = true;
	
	private StatTableModel loaded = null;
	
	private boolean quiet = false;
	
	private String error = null;
	
	public LoadDracoSQL(String filename, WorksheetHandler parent) {
		this.filename = filename;
		current_step = 1;
		this.parent = parent;
	}
	
	public void load() {
		parent.setUpdatableTable(false);
		parent.setVisibleDesktop(false);
		new IOFileWorkerDialog(this).setVisible(true);
		
		// Set the table to viewable again
		Runnable resetUpdateable = new Runnable() {
            public void run() {
            	parent.setUpdatableTable(true);
            	parent.setVisibleDesktop(true);
            }
        };
        SwingUtilities.invokeLater(resetUpdateable);
		
	}

	public StatTableModel getLoadedData() {
		return loaded;
	}
	
	public String getWorkerTitle() {
		return LOAD_WORKSHEET_TITLE;
	}

	public void doStep() {

		try {
			switch(current_step) {
				case 1:
	
					// Need to check if the file exists first!
					File f = new File(filename);
					if(!f.exists())
						success = false;
					else
						sql = new DracoSQLRead(filename);
					break;
				case 2:
					loaded = sql.loadModel();
					break;
				case 3:
					success = success && sql.loadConstants(loaded);
					break;
				case 4:
					success = success && sql.loadAnalyses(parent, loaded);
					break;
				case 5:
					success = success && sql.loadRegressions(parent, loaded);
					break;
				case 6:
					success = success && sql.loadPlots(parent);
					break;
				case 7:
					success = success && sql.loadTexts(parent);
					break;
				case 8:
					success = success && sql.loadPlugins(parent);
				case 9:
					sql.close();
					break;
				default:
					success = false;
			}
		} catch (IllegalStateException ise) {
			System.err.println("NestedVM failed during load...");
			ise.printStackTrace();
			success = false;
			error = "Problem during data loading.\n" +
			"Please report the issue to\n"   +
			"support@approximatrix.com";
		}
		current_step++;
		
		// Not necessary
		//parent.updateWindowNames();
	}

	public int getStepNumber() {
		return current_step;
	}

	public int getTotalSteps() {
		return TOTAL_STEPS;
	}

	public String getStatus() {
		return LOAD_STEPS[current_step-1];
	}
	
	public JFrame getParentWindow() {
		if(parent instanceof JFrame)
			return (JFrame)parent;
		else
			return null;
	}
	
	public boolean stepSuccess() {
		return success;
	}

	public String getError() {
		return error;
	}

	public void setQuiet(boolean value) {
		quiet = value;
	}
}
