package industries.doublehelix.furrynotemanager;

import java.io.IOException;
import java.net.CookieHandler;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import industries.doublehelix.furrynotemanager.gui.MainFrame;
import industries.doublehelix.furrynotemanager.siteImporters.ListCookieHandler;

public class FurryNoteManager {
	private Path workingDir = Paths.get(System.getProperty("user.home") + "/.FurryNoteManager/");

	public static void main(String[] args) {
		new FurryNoteManager();
	}
	
	public FurryNoteManager() {
		initWorkingDir();
		CookieHandler.setDefault(new ListCookieHandler());
		
		try {
			// init db
			DBTools.getInstance();
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "Could not init the DB, maybe you started this program already?", "Error", JOptionPane.ERROR_MESSAGE);
			System.exit(-1);
		}
		
		Thread hook = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
	                DriverManager.getConnection("jdbc:derby:;shutdown=true");
	            } catch (SQLException se) {
	                if (( (se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState()) ))) {
	                    // we got the expected exception, all is well
	                } else {
	                    System.err.println("Derby did not shut down normally");
	                    se.printStackTrace();
	                }
	            }
			}
		});
		Runtime.getRuntime().addShutdownHook(hook);
		
		new MainFrame();
	}
	
	private void initWorkingDir() {
		// if it's there but a file, delete it
		if (Files.exists(workingDir) && !Files.isDirectory(workingDir)) {
			try {
				Files.delete(workingDir);
			} catch (IOException e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, workingDir.toString() + " exists but is not a directory and can't be deleted, please delete it manually and restart FurryCrossposter", "FurryCrossposter", JOptionPane.ERROR_MESSAGE);
				System.exit(-1);
			}
		}
		
		// if it's not there or was a file and therefore deleted, make it
		if (!Files.exists(workingDir)) {
			try {
				Files.createDirectory(workingDir);
			} catch (IOException e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, "Could not create " + workingDir.toString(), "FurryCrossposter", JOptionPane.ERROR_MESSAGE);
				System.exit(-1);
			}
		}
		
		DBTools.setDatabasePath(workingDir.toString());
		//System.setProperty("derby.system.home", workingDir.toString());
		//System.setProperty("derby.stream.error.file", "db.log");
	}

}
