package de.siphalor.was.visual.canvas.layout;

import org.jetbrains.annotations.Nullable;

import java.awt.*;

public class FixedAspectLayout implements LayoutManager {
	/**
	 * Width through height
	 */
	private final double aspectRatio;
	@Nullable
	private Component component;

	public FixedAspectLayout(double aspectRatio) {
		this(aspectRatio, null);
	}

	public FixedAspectLayout(double aspectRatio, @Nullable Component component) {
		this.aspectRatio = aspectRatio;
		this.component = component;
	}

	@Override
	public void addLayoutComponent(String name, Component comp) {
		component = comp;
	}

	@Override
	public void removeLayoutComponent(Component comp) {
		if (component == comp)
			component = null;
	}

	@Override
	public Dimension preferredLayoutSize(Container parent) {
		return parent.getSize();
	}

	@Override
	public Dimension minimumLayoutSize(Container parent) {
		return parent.getSize();
	}

	@Override
	public void layoutContainer(Container parent) {
		if (component != null) {
			Insets insets = parent.getInsets();
			int width = parent.getWidth() - (insets.left + insets.right);
			int height = parent.getHeight() - (insets.top + insets.bottom);

			int calc = (int) (height * aspectRatio);
			if (calc <= width) {
				component.setBounds(insets.left + (width - calc) / 2, insets.top, calc, height);
			} else {
				calc = (int) (width / aspectRatio);
				component.setBounds(insets.left, insets.top + (height - calc) / 2, width, calc);
			}
		}
	}
}
