package jp.ac.iwatepu.soner.gui;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;

import javafx.concurrent.Task;
import jp.ac.iwatepu.soner.DBConnector;
import jp.ac.iwatepu.soner.Util;
import jp.ac.iwatepu.soner.processing.JenaFoafParser;

/**
 * Controller for the processing task.
 * @author gajop
 *
 */
public class ProcessingController extends AbstractWizardStepController {

	@Override
	public void initialize(URL location, ResourceBundle resources) {	
		super.initialize(location, resources);
	}
	
	@Override
	protected Task<Integer> createTask() {
		Task<Integer> task = new Task<Integer>() {
			@Override
			protected void updateMessage(String message) {
				logger.info(message);
				super.updateMessage(message);
			}
			
		    @Override protected Integer call() throws Exception {
		    	updateMessage("Loading files into memory...");
		    	JenaFoafParser jenaFOAFParser = new JenaFoafParser() {
		    		@Override
		    		public void parsedDocument(int totalDocuments,
		    				int parsedDocuments) {
		    			super.parsedDocument(totalDocuments, parsedDocuments);
						updateMessage(parsedDocuments + "/" + totalDocuments);
						updateProgress(parsedDocuments, totalDocuments);
		    		}
		    	};
		    	jenaFOAFParser.run();
		    	updateProgress(100, 100);
		    	
		    	try {
			    	if (Util.getInstance().getDbDriver().equals("org.sqlite.JDBC")) {
			    		updateMessage("Executing SQL scripts (this can take a while): Purify URIs");
			    		executeSql("main/resources/sql/purify_uri_sqlite.sql");			    		
			    	} else {
			    		executeSql("main/resources/sql/purify_uri.sql");
			    	}
			    	updateMessage("Executing SQL scripts (this can take a while): Cleanup Known IDs");
			    	executeSql("main/resources/sql/known_ids.sql");			    	
			    	updateMessage("Executing SQL scripts (this can take a while): Synonym script");
			    	executeSql("main/resources/sql/synonym_script.sql");
			    	updateMessage("Executing SQL scripts (this can take a while): Purify attributes");
			    	DBConnector.getInstance().createPurifiedAttributes();
			    	updateMessage("Executing SQL scripts: Finished");
			    	done();
			    	addOutput("People: " + DBConnector.getInstance().getPeopleSize());
			    	addOutput("Known relationships: " + DBConnector.getInstance().getKnownPeopleSize());
			    	addOutput("Synonym size: " + DBConnector.getInstance().getSynonymSize());
		    	} catch (Throwable t) { 
		    		logger.error(t);
		    		t.printStackTrace();
		    		System.exit(-1);
		    	}

		    	updateMessage("Done");		    	
				return 0;
		    }
		};
		return task;
	}

	@Override
	protected String nextStepName() {
		return "Tagging.fxml";
	}
	
	private void executeSql(String sqlFilePath) {
	    final class SqlExecuter extends SQLExec {
	        public SqlExecuter() {
	            Project project = new Project();
	            project.init();
	            setProject(project);
	            setTaskType("sql");
	            setTaskName("sql");
	        }
	    }

	    SqlExecuter executer = new SqlExecuter();
	    ClassLoader classLoader = getClass().getClassLoader();
	    executer.setSrc(new File(classLoader.getResource(sqlFilePath).getFile()));
	    executer.setDriver(Util.getInstance().getDbDriver());

		String user = Util.getInstance().getDbUser();
		String password = "";
		if (!user.equals("")) {
			user = "?user=" + user;
			password = Util.getInstance().getDbPassword();
			if (!password.equals("")) {
				password = "&password=" + password;
			}
		}
		String connectionPath = Util.getInstance().getDbURL() + user + password;
		
		executer.setUserid(Util.getInstance().getDbUser());
		executer.setPassword(Util.getInstance().getDbPassword());
	    executer.setUrl(connectionPath);
	    executer.setEscapeProcessing(false);
	    executer.execute();
	}


}

@@ -42,20 +42,174 @@
 java.io.
-File
+BufferedReader;%0Aimport java.io.File;%0Aimport java.io.FileOutputStream;%0Aimport java.io.InputStream;%0Aimport java.io.InputStreamReader;%0Aimport java.io.PrintWriter
 ;%0Aimport
@@ -3260,56 +3260,8 @@
    %7D
-%0A%0A%09    SqlExecuter executer = new SqlExecuter();
 %0A%09  
@@ -3326,33 +3326,25 @@
     
-executer.setSrc(new File(
+InputStream in = 
 clas
@@ -3362,16 +3362,24 @@
 Resource
+AsStream
 (sqlFile
@@ -3387,19 +3387,532 @@
 ath)
-.getFile())
+; %0A%09    BufferedReader reader = new BufferedReader(new InputStreamReader(in));%0A%09    final File tempFile;%0A%09    try %7B%0A%09    %09tempFile = File.createTempFile(%22__temp%22, %22.sql%22);%0A%09    %09PrintWriter pw = new PrintWriter(tempFile);%0A%09        for (String line = reader.readLine(); line != null; line = reader.readLine()) %7B%0A%09        %09pw.write(line + %22%5Cn%22);%0A%09        %7D%0A%09        pw.close();%0A%09    %7D catch (Exception ex) %7B%0A%09    %09return;%0A%09    %7D%0A        %0A%09    %0A%09    SqlExecuter executer = new SqlExecuter();%0A%09    %0A%09    executer.setSrc(tempFile
 );%0A%09
@@ -4493,24 +4493,24 @@
 ing(false);%0A
-
 %09    execute
@@ -4522,15 +4522,39 @@
 cute();%0A
+%09    tempFile.delete();%0A
 %09%7D%0A%0A%0A%7D%0A

make SQL executable from resources (2nd attempt)