package control;

import boundary.*;
import entity.*;
import org.w3c.dom.Document;

/* The UC1Controller is an "Observer" of the SUDTimer
 * It is actually in charge of both UC1 and UC6, since
 * it was convenient to place both in a single controller
 */
public class UC1Controller implements Observer {
	
	private Subject mySubject;
	private static String xmlString;
	private static Document xmlDocument;
	private static XMLReader xmlReader;
	public UC1Controller(Subject timer) {
		mySubject = timer;
		mySubject.registerObserver(this);
	}
	
	// insert the first stock symbols
	public static void insertFirstStockSymbols() {
		if (xmlReader.insertSelfAsFirstStocks()) {
			System.out.println("Database init successful.");
		}
		else {
			System.err.println("Database init failed.");
		}
	}
	
	public static boolean uc1() {
		boolean retval = false;
		System.out.println("\nRunning UC1...");
		// in case Server Admin exits in middle of process
		try {
			xmlString = PerlCommunicator.fetchStocks();
			xmlDocument = XMLParser.parseString(xmlString);
			xmlReader = new XMLReader(xmlDocument);
			if (DatabaseCommunicator.isDatabaseEmpty()) {
				System.out.println("Populating stock database...");
				UC1Controller.insertFirstStockSymbols();
				System.out.println("Inserted stock symbols.");
				retval = true;
			}
			else if (xmlReader.writeSelfToDatabase()) {
				System.out.println("Database update successful.");
				retval = true;
			}
			else {
				System.err.println("Database update failed. Please check your Internet connection.");
			}
		}
		catch (Exception e) {
			
		}
		return retval;
	}
	
	// the update() method is called when the Subject notifies its Observers
	public void update() {
		UC1Controller.uc1();
		SystemMenu.printQuitMenu();
	}
	/*
	public static void main(String[] args) {
		System.out.println(isDatabaseEmpty());
	}
	*/

}