// Copyright (c) 2022, JINGROW and Contributors
// MIT License. See LICENSE

jingrow.ui.form.LinkedWith = class LinkedWith {
	constructor(opts) {
		$.extend(this, opts);
	}

	show() {
		if (!this.dialog) this.make_dialog();

		$(this.dialog.body).html(
			`<div class="text-muted text-center" style="padding: 30px 0px">
				${__("Loading")}...
			</div>`
		);

		this.dialog.show();
	}

	make_dialog() {
		this.dialog = new jingrow.ui.Dialog({
			title: __("Linked With"),
		});

		this.dialog.on_page_show = () => {
			jingrow
				.xcall("jingrow.desk.form.linked_with.get", {
					pagetype: this.frm.pagetype,
					pagename: this.frm.pagename,
				})
				.then((r) => {
					this.frm.__linked_pgs = r;
				})
				.then(() => this.make_html());
		};
	}

	make_html() {
		let html = "";
		const linked_pgs = this.frm.__linked_pgs;
		const linked_pagetypes = Object.keys(linked_pgs);

		if (linked_pagetypes.length === 0) {
			html = __("Not Linked to any record");
		} else {
			html = linked_pagetypes
				.map((pagetype) => {
					const pgs = linked_pgs[pagetype];
					return `
					<div class="list-item-table margin-bottom">
						${this.make_pg_head(pagetype)}
						${pgs.map((pg) => this.make_pg_row(pg, pagetype)).join("")}
					</div>
				`;
				})
				.join("");
		}

		$(this.dialog.body).html(html);
	}

	make_pg_head(heading) {
		return `
			<header class="level list-row list-row-head text-muted small">
				<div>${__(heading)}</div>
			</header>
		`;
	}

	make_pg_row(pg, pagetype) {
		return `<div class="list-row-container">
			<div class="level list-row small">
				<div class="level-left bold">
					<a href="/app/${jingrow.router.slug(pagetype)}/${pg.name}">${pg.name}</a>
				</div>
			</div>
		</div>`;
	}
};
