package net.oni2.aeinstaller.gui.toolmanager;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ResourceBundle;
import java.util.TreeSet;

import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;

import net.oni2.SettingsManager;
import net.oni2.aeinstaller.backend.RuntimeOptions;
import net.oni2.aeinstaller.backend.oni.management.tools.ToolsManager;
import net.oni2.aeinstaller.backend.packages.Package;
import net.oni2.aeinstaller.gui.downloadwindow.Downloader;
import net.oni2.aeinstaller.gui.modtable.ModSelectionListener;
import net.oni2.aeinstaller.gui.modtable.ModTable;
import net.oni2.aeinstaller.gui.modtable.ModTable.ETableContentType;
import net.oni2.aeinstaller.gui.packageinfobox.PackageInfoBox;
import net.oni2.resourcebundle.UTF8ResourceBundleLoader;

import org.javabuilders.BuildResult;
import org.javabuilders.swing.SwingJavaBuilder;

/**
 * @author Christian Illy
 */
public class ToolManager extends JDialog implements ModSelectionListener {
	private static final long serialVersionUID = 343221630538866384L;

	private ResourceBundle bundle = UTF8ResourceBundleLoader
			.getBundle("net.oni2.aeinstaller.localization."
					+ getClass().getSimpleName());
	@SuppressWarnings("unused")
	private BuildResult result = SwingJavaBuilder.build(this, bundle);

	private JSplitPane contents;

	private JScrollPane scrollTools;
	private ModTable tblTools;

	private PackageInfoBox pkgInfo;
	private JButton btnInstall;

	private Icon icoInstall = null;
	private Icon icoUninstall = null;

	private Package selectedPackage = null;

	/**
	 * Open the dialog
	 */
	public ToolManager() {
		AbstractAction closeAction = new AbstractAction() {

			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		};
		KeyStroke ksCtrlW = KeyStroke
				.getKeyStroke('W', KeyEvent.CTRL_DOWN_MASK);
		getRootPane()
				.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
				.put(ksCtrlW, "close");
		getRootPane().getActionMap().put("close", closeAction);

		contents.setDividerLocation(SettingsManager.getInstance().get(
				"win_tools_divloc", 550));
		contents.setResizeWeight(0.4);

		tblTools = new ModTable(ETableContentType.TOOLS);
		tblTools.reloadData();
		scrollTools.setViewportView(tblTools);

		tblTools.addModSelectionListener(this);

		icoInstall = new ImageIcon(getClass().getResource(
				SwingJavaBuilder.getConfig().getResource("img.install")));
		icoUninstall = new ImageIcon(getClass().getResource(
				SwingJavaBuilder.getConfig().getResource("img.uninstall")));

		setSize(SettingsManager.getInstance().get("win_tools_width", 950),
				SettingsManager.getInstance().get("win_tools_height", 600));
		setLocationRelativeTo(null);
	}

	@SuppressWarnings("unused")
	private void install() {
		if (selectedPackage != null) {
			if (selectedPackage.isInstalled()) {
				TreeSet<Package> tools = new TreeSet<Package>();
				tools.add(selectedPackage);
				ToolsManager.installTools(tools, true);
			} else {
				if (!selectedPackage.isLocalAvailable()) {
					if (RuntimeOptions.isOfflineMode()) {
						JOptionPane.showMessageDialog(this,
								bundle.getString("offlineMode.text"),
								bundle.getString("offlineMode.title"),
								JOptionPane.WARNING_MESSAGE);
						return;
					}

					TreeSet<Package> toDownload = new TreeSet<Package>();
					toDownload.add(selectedPackage);

					Downloader dl = new Downloader(toDownload, null, false);
					try {
						dl.setVisible(true);
						if (!dl.isFinished())
							return;
					} finally {
						dl.dispose();
					}
				}

				TreeSet<Package> tools = new TreeSet<Package>();
				tools.add(selectedPackage);
				ToolsManager.installTools(tools, false);
			}
		}
		modSelectionChanged(tblTools, selectedPackage);
	}

	@Override
	public void modSelectionChanged(ModTable source, Package mod) {
		selectedPackage = mod;

		pkgInfo.updateInfo(mod);
		if (mod != null) {
			btnInstall.setEnabled(true);
			if (mod.isInstalled()) {
				btnInstall.setText(bundle.getString("btnInstall.un.text"));
				btnInstall.setToolTipText(bundle
						.getString("btnInstall.un.tooltip"));
				btnInstall.setIcon(icoUninstall);
			} else {
				btnInstall.setText(bundle.getString("btnInstall.text"));
				btnInstall.setToolTipText(bundle
						.getString("btnInstall.tooltip"));
				btnInstall.setIcon(icoInstall);
			}
		}
	}

	@SuppressWarnings("unused")
	private void closing() {
		SettingsManager.getInstance().put("win_tools_divloc",
				contents.getDividerLocation());
		SettingsManager.getInstance().put("win_tools_width", getWidth());
		SettingsManager.getInstance().put("win_tools_height", getHeight());
	}
}
