package net.oni2.aeinstaller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

import net.oni2.ProxySettings;
import net.oni2.SettingsManager;
import net.oni2.aeinstaller.backend.CaseInsensitiveFile;
import net.oni2.aeinstaller.backend.LogPrintStream;
import net.oni2.aeinstaller.backend.Paths;
import net.oni2.aeinstaller.backend.RuntimeOptions;
import net.oni2.aeinstaller.backend.SizeFormatter;
import net.oni2.aeinstaller.backend.oni.OniSplit;
import net.oni2.aeinstaller.backend.oni.management.Installer;
import net.oni2.aeinstaller.gui.MainWin;
import net.oni2.moddepot.DepotManager;
import net.oni2.platformtools.PlatformInformation;
import net.oni2.platformtools.PlatformInformation.Platform;
import net.oni2.platformtools.applicationinvoker.ApplicationInvoker;
import net.oni2.platformtools.applicationinvoker.DotNet;
import net.oni2.platformtools.applicationinvoker.EExeType;
import net.oni2.resourcebundle.UTF8ResourceBundleLoader;
import net.oni2.svnaccess.SVN;
import net.oni2.swingcomponents.HTMLLinkLabel;

import org.javabuilders.swing.SwingJavaBuilder;
import org.simplericity.macify.eawt.Application;
import org.simplericity.macify.eawt.DefaultApplication;

/**
 * @author Christian Illy
 */
public class AEInstaller2 {

	private static ResourceBundle imagesBundle = ResourceBundle
			.getBundle("net.oni2.aeinstaller.Images");
	private static ResourceBundle basicBundle = ResourceBundle
			.getBundle("net.oni2.aeinstaller.AEInstaller");
	private static ResourceBundle globalBundle;

	private static Application app = null;

	private static void initMacOS() {
		System.setProperty("apple.laf.useScreenMenuBar", "true");
		System.setProperty("com.apple.mrj.application.apple.menu.about.name",
				basicBundle.getString("appname"));
		app = new DefaultApplication();

		URL icon = AEInstaller2.class.getResource(imagesBundle
				.getString("img.ae"));
		try {
			BufferedImage img = ImageIO.read(icon);
			app.setApplicationIconImage(img);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void initBundles() {
		File localesDir = CaseInsensitiveFile.getCaseInsensitiveFile(
				Paths.getInstallerPath(), "locales");
		if (localesDir.isDirectory())
			addClassPath(localesDir);
		else {
			File localesSubDir = CaseInsensitiveFile.getCaseInsensitiveFile(
					CaseInsensitiveFile.getCaseInsensitiveFile(
							Paths.getInstallerPath(), "bin"), "locales");
			if (localesSubDir.isDirectory()) {
				addClassPath(localesSubDir);
			}
		}
		globalBundle = UTF8ResourceBundleLoader
				.getBundle("net.oni2.aeinstaller.localization.Global");
	}

	private static void addClassPath(File dir) {
		try {
			URL u = dir.toURI().toURL();
			URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader
					.getSystemClassLoader();
			Class<URLClassLoader> urlClass = URLClassLoader.class;
			Method method = urlClass.getDeclaredMethod("addURL",
					new Class[] { URL.class });
			method.setAccessible(true);
			method.invoke(urlClassLoader, new Object[] { u });
		} catch (MalformedURLException e) {
		} catch (SecurityException e) {
		} catch (NoSuchMethodException e) {
		} catch (IllegalArgumentException e) {
		} catch (IllegalAccessException e) {
		} catch (InvocationTargetException e) {
		}
	}

	/**
	 * @param args
	 *            Command line arguments
	 */
	public static void main(String[] args) {
		Paths.getPrefsPath().mkdirs();
		Paths.getDownloadPath().mkdirs();

		for (String a : args) {
			if (a.equalsIgnoreCase("-debug"))
				RuntimeOptions.setDebug(true);
			if (a.equalsIgnoreCase("-nocacheupdate"))
				RuntimeOptions.setNoCacheUpdateMode(true);
			if (a.equalsIgnoreCase("-offline"))
				RuntimeOptions.setOfflineMode(true);
			if (a.equalsIgnoreCase("-usewd"))
				RuntimeOptions.setUseWorkingDir(true);
		}
		LogPrintStream lps = LogPrintStream.getInstance();
		if (!RuntimeOptions.isDebug()) {
			try {
				lps.setFile(new File(Paths.getPrefsPath(), "aei_output.log"));
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (PlatformInformation.getPlatform() == Platform.MACOS)
			initMacOS();

		SettingsManager.deserializeFromFile(Paths.getSettingsFilename());

		if (Paths.getProxySettingsFilename().exists()) {
			ProxySettings.deserializeFromFile(Paths.getProxySettingsFilename());
		}

		initBundles();

		SwingJavaBuilder.getConfig().addResourceBundle(imagesBundle);
		SwingJavaBuilder.getConfig().addResourceBundle(basicBundle);
		SwingJavaBuilder.getConfig().addResourceBundle(globalBundle);
		SwingJavaBuilder.getConfig().setMarkInvalidResourceBundleKeys(true);
		SwingJavaBuilder.getConfig().addType("JToolBarSeparator",
				JToolBar.Separator.class);

		System.setProperty("networkaddress.cache.ttl", "5");
		System.setProperty("networkaddress.cache.negative.ttl", "1");

		try {
			String laf = SettingsManager.getInstance().get("lookandfeel",
					(String) null);
			if (laf == null) {
				if (PlatformInformation.getPlatform() != Platform.LINUX) {
					laf = UIManager.getSystemLookAndFeelClassName();
				} else {
					for (LookAndFeelInfo lafInfo : UIManager
							.getInstalledLookAndFeels()) {
						if (lafInfo.getName().equals("Nimbus"))
							laf = lafInfo.getClassName();
					}
				}
			}
			if (laf == null)
				laf = UIManager.getSystemLookAndFeelClassName();
			UIManager.setLookAndFeel(laf);
		} catch (Exception e) {
			e.printStackTrace();
		}
		JFrame.setDefaultLookAndFeelDecorated(true);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(basicBundle.getString("appname")
				+ basicBundle.getString("appversion"));
		System.out.println("Time:      " + sdf.format(new Date()));
		System.out.println("Java:      \""
				+ System.getProperty("java.runtime.name") + "\" v. "
				+ System.getProperty("java.version") + " by \""
				+ System.getProperty("java.vendor") + "\" (spec. "
				+ System.getProperty("java.specification.version") + ")");
		System.out.println("Java home: " + System.getProperty("java.home"));
		System.out.println("Command:   "
				+ System.getProperty("sun.java.command"));
		System.out.println("JarPath:   " + Paths.getJarPath());
		System.out.println("PrefsPath: " + Paths.getPrefsPath());
		System.out.println("DataPath:  " + Paths.getModsPath());
		System.out.println("DownPath:  " + Paths.getDownloadPath());
		System.out.println("TempPath:  " + Paths.getTempPath());
		System.out.println("ValidPath: " + Installer.verifyRunningDirectory());
		System.out.println("Platform:  " + PlatformInformation.getPlatform());
		System.out.println("Architect: "
				+ PlatformInformation.getArchitecture());
		System.out.println(".NET:      " + DotNet.isInstalled());
		System.out.println("OniSplit:  " + OniSplit.isOniSplitInstalled());
		System.out.println("Globalized:" + Installer.isEditionInitialized());

		// TODO: Check available space
		System.out
				.println("Free space on temp: "
						+ SizeFormatter.format(Paths.getTempPath()
								.getUsableSpace(), 3));
		System.out.println("Free space on Jar:  "
				+ SizeFormatter.format(Paths.getInstallerPath()
						.getUsableSpace(), 3));
		System.out.println();

		if (!DotNet.isInstalled()) {
			HTMLLinkLabel hll = new HTMLLinkLabel();
			String dlUrl = "";
			switch (PlatformInformation.getPlatform()) {
				case WIN:
					switch (PlatformInformation.getArchitecture()) {
						case X86:
							dlUrl = "http://download.microsoft.com/download/c/6/e/c6e88215-0178-4c6c-b5f3-158ff77b1f38/NetFx20SP2_x86.exe";
							break;
						case AMD64:
							dlUrl = "http://download.microsoft.com/download/c/6/e/c6e88215-0178-4c6c-b5f3-158ff77b1f38/NetFx20SP2_x64.exe";
							break;
					}
					break;
				default:
					dlUrl = "http://www.go-mono.com/mono-downloads/download.html";
			}
			hll.setText(globalBundle
					.getString("dotNetMissing.text")
					.replaceAll(
							"%1",
							String.format("<a href=\"%s\">%s</a>", dlUrl, dlUrl)));
			JOptionPane.showMessageDialog(null, hll,
					globalBundle.getString("dotNetMissing.title"),
					JOptionPane.ERROR_MESSAGE);
			return;
		}

		if (!Installer.verifyRunningDirectory()) {
			JOptionPane.showMessageDialog(null,
					globalBundle.getString("invalidPath.text"),
					globalBundle.getString("invalidPath.title"),
					JOptionPane.ERROR_MESSAGE);
			if (!RuntimeOptions.isDebug()) {
				return;
			}
		}

		if (!RuntimeOptions.isOfflineMode()) {
			RuntimeOptions.setOfflineMode(!DepotManager.getInstance()
					.checkConnection());
		}
		if (RuntimeOptions.isOfflineMode()) {
			JOptionPane.showMessageDialog(null,
					globalBundle.getString("offlineModeStartup.text"),
					globalBundle.getString("offlineModeStartup.title"),
					JOptionPane.INFORMATION_MESSAGE);
		}

		if (!RuntimeOptions.isOfflineMode()) {
			SVN svn = new SVN();
			try {
				int x = svn.checkSVN("http://svn.aei.oni2.net",
						Paths.getJarPath());
				if (x > 0) {
					// Update available or missing files
					int res = JOptionPane.showConfirmDialog(null,
							globalBundle.getString("aeiUpdateAvailable.text"),
							globalBundle.getString("aeiUpdateAvailable.title"),
							JOptionPane.YES_NO_OPTION,
							JOptionPane.INFORMATION_MESSAGE);
					if (res == JOptionPane.YES_OPTION) {
						File updater = new File(Paths.getInstallerPath(),
								"AEInstaller2Updater.jar");
						ApplicationInvoker.execute(EExeType.JAR, null, updater,
								null, false);
						return;
					}
				} else if (x == 0) {
					// Up to date
				} else if (x < 0) {
					// No WC at given path
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					MainWin mw = new MainWin();
					if (app != null) {
						app.addAboutMenuItem();
						app.setEnabledAboutMenu(true);
						app.addPreferencesMenuItem();
						app.setEnabledPreferencesMenu(true);
						app.addApplicationListener(mw);
					}
					mw.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}
}
