package jin;

import java.io.*;
import java.util.*;

public class LoadThread extends Thread {

	JIN theApp;
	
	LoadThread(JIN win) {
		theApp = win;
	}
	
	public void run() {
		// Main Menu
		setTask("Main Menu...");
		theApp.frmMain = new jin.MainMenu.MainFrame(theApp);
		
		// Options Dialog
		setTask("Options Dialog...");
		theApp.frmOptions = new jin.OptionDialog.OptionFrame(theApp);
		
		// Install Wizard
		setTask("Install Wizard...");
		theApp.frmWizard = new jin.InstallWizard.InstallWizard(theApp);
		
		// Configuration File
		setTask("Configuration File...");
		loadConf(theApp.frmOptions);
		
		theApp.launchProgram();
	}
	
	private void setTask(String task) {
		theApp.pnlStat.lblStat.setText(task);
	}
	
	private void loadConf(jin.OptionDialog.OptionFrame optFrame) {
		int osCount = countOSes();
		Object os[] = new Object[osCount];
		optFrame.osCnt = osCount;
		int loc = 0;
		
		try {
			BufferedReader in = new BufferedReader(new FileReader("JIN.conf"));
			
			for(;;) {
				String temp = in.readLine();
				
				if(temp == null)
					break;
				else {
					if(temp.trim().toUpperCase().startsWith("[SYSMANIFEST]"))
						optFrame.setSysManifest(deriveEnd(temp));
					else if(temp.trim().toUpperCase().startsWith("[OSTYPE]"))
						os[loc++] = new String(deriveOS(deriveEnd(temp)));
				}
			}
			
			optFrame.invalidateOS(os);
			optFrame.updateSettings();
			in.close();
		}
		
		catch(Exception x) {
			System.err.println(x);
		}
	}
	
	private int countOSes() {
		int result = 0;
	
		try {
			BufferedReader in = new BufferedReader(new FileReader("JIN.conf"));
			
			for(;;) {
				String temp = in.readLine();
				
				if(temp == null)
					break;
				else {
					if(temp.trim().toUpperCase().startsWith("[OSTYPE]"))
						result++;
				}
			}
			
			in.close();
		}
		
		catch(Exception OSFuckUp) {
			System.err.println(OSFuckUp);
		}
		
		return result;
	}
	
	private String deriveOS(String fn) {
		String result = "No Name";
		
		try {
			BufferedReader inOS = new BufferedReader(new FileReader(fn));
			
			for(;;) {
				String temp = inOS.readLine();
				
				if(temp == null)
					break;
				else {
					if(temp.trim().toUpperCase().startsWith("[OSNAME]"))
						result = deriveEnd(temp);
				}
			}
			
			inOS.close();
		}
		
		catch(Exception deriveOSErr) {
			System.err.println(deriveOSErr);
		}
		
		return (result + ":" + fn);
	}
	
	private String deriveEnd(String line) {
		StringTokenizer t = new StringTokenizer(line, "=");
		String result = t.nextToken();
		result = t.nextToken().trim();
		
		return result;
	}

}