// Copyright (c) 2015, JINGROW and Contributors
// MIT License. See license.txt

jingrow.ui.form.on("Website Slideshow", {
	refresh: (frm) => {
		let intro = frm.pg.__islocal
			? __("First set the name and save the record.")
			: __("Attach files / urls and add in table.");
		frm.set_intro(intro);

		if (frm.is_new()) return;

		frm.add_custom_button(__("Fetch attached images from document"), () => {
			const d = new jingrow.ui.Dialog({
				title: __("Fetch Images"),
				fields: [
					{
						label: __("PageType"),
						fieldtype: "Link",
						fieldname: "reference_pagetype",
						options: "PageType",
						reqd: 1,
					},
					{
						label: __("Name"),
						fieldtype: "Dynamic Link",
						fieldname: "reference_name",
						options: "reference_pagetype",
						reqd: 1,
					},
				],
				primary_action_label: __("Add to table"),
				primary_action: ({ reference_pagetype, reference_name }) => {
					jingrow.db
						.get_list("File", {
							fields: ["file_url"],
							filters: {
								attached_to_pagetype: reference_pagetype,
								attached_to_name: reference_name,
							},
						})
						.then((images) => {
							frm.pg.slideshow_items = frm.pg.slideshow_items || [];
							images.forEach((image) => {
								frm.pg.slideshow_items.push({
									image: image.file_url,
								});
							});

							frm.refresh_field("slideshow_items");
							d.hide();
						});
				},
			});

			d.show();
		});
	},
});
