use ui;
use layout;
use core:info;
use core:geometry;

dialog OverviewDialog {
	layout Grid {
		expandCol: 0;

		Label info("") {}
		nextLine;
		Label author("") {}
		nextLine;
		Label licLabel("Main license:") {}
		nextLine;
		Button licButton("") {}

		nextLine;
		Label l("Other licenses:") {}
		nextLine;
		expandRow;
		ScrollWindow scroll(LicenseList(), Size(100, 100)) {}
	}

	init(ProgramInfo info) {
		init("About ${info.name}", Size(200, 100)) {}

		if (version = info.version)
			this.info.text = "${info.name} ${version}";
		else
			this.info.text = info.name;

		author.text = "By: ${info.author}";

		if (license = info.license) {
			var me = this;
			licButton.text = license.title;
			Fn<void> cb = () => LicenseDialog(license).show(me);
			licButton.onClick = cb;
		} else {
			licLabel.visible = false;
			licButton.visible = false;
		}

		if (buttons = scroll.content as LicenseList) {
			for (l in core:info:licenses()) {
				if (l !is info.license) {
					buttons.add(this, l);
				}
			}
		}
	}
}

class LicenseList extends Container {
	init() {
		init() {}
	}

	// Buttons. One for each license.
	private Button[] buttons;

	// Add a button.
	void add(Frame owner, License l) {
		Button b(l.name);
		buttons << b;
		add(b);

		var me = this;
		b.onClick = () => me.showLicense(owner, l);
	}

	// Show a license.
	void showLicense(Frame owner, License l) {
		LicenseDialog dlg(l);
		dlg.show(owner);
	}

	// Update size.
	void resized(Size size) : override {
		Float y = 0;
		for (b in buttons) {
			Size s = b.minSize;
			b.pos = Rect(0, y, size.w, y + s.h);
			y += s.h + 8;
		}
	}

	// Update minimum size.
	Size minSize() : override {
		Size min;
		for (b in buttons) {
			Size s = b.minSize;
			min.w = max(min.w, s.w);
			min.h += 8 + s.h;
		}
		min.h -= 8;
		min;
	}
}
