package org.spview.preferences;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.prefs.Preferences;

import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class WindowHandler {
	public static void registerFrame(JFrame frame, String frameUniqueId, int defaultX, int defaultY, int defaultW,
			int defaultH) {

		Preferences prefs = Preferences.userRoot().node(WindowHandler.class.getSimpleName() + "-" + frameUniqueId);
		Dimension savedDim = getFrameSize(prefs, defaultW, defaultH);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		// The following test is needed on macOS.
		if ((savedDim.getWidth() >= screenSize.getWidth()) || (savedDim.getHeight() >= screenSize.getHeight())) {
			frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
		} else {
			frame.setSize(savedDim);
			frame.setLocation(getFrameLocation(prefs, defaultX, defaultY));
		}

		CoalescedEventUpdater updater = new CoalescedEventUpdater(400, () -> updatePref(frame, prefs));

		frame.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				updater.update();
			}

			@Override
			public void componentMoved(ComponentEvent e) {
				updater.update();
			}
		});
	}

	public static void setLookAndFeel() {

		if (isMacOS()) {

			// take the menu bar off the jframe
			System.setProperty("apple.laf.useScreenMenuBar", "true");

			// set the look and feel
			try {
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
					| UnsupportedLookAndFeelException e) {
				e.printStackTrace();
			}
		}
	}

	private static boolean isMacOS() {
		String lcOSName = System.getProperty("os.name").toLowerCase();
		return lcOSName.startsWith("mac os x");
	}

	private static void updatePref(JFrame frame, Preferences prefs) {
//		System.out.println("Updating preferences");
		Point location = frame.getLocation();
		prefs.putInt("x", location.x);
		prefs.putInt("y", location.y);
		Dimension size = frame.getSize();
		prefs.putInt("w", size.width);
		prefs.putInt("h", size.height);
	}

	private static Dimension getFrameSize(Preferences pref, int defaultW, int defaultH) {
		int w = pref.getInt("w", defaultW);
		int h = pref.getInt("h", defaultH);
		return new Dimension(w, h);
	}

	private static Point getFrameLocation(Preferences pref, int defaultX, int defaultY) {
		int x = pref.getInt("x", defaultX);
		int y = pref.getInt("y", defaultY);
		return new Point(x, y);
	}
}