// Copyright (c) 2016, JINGROW
// For license information, please see license.txt

jingrow.ui.form.on("Bulk Update", {
	refresh: function (frm) {
		frm.set_query("document_type", function () {
			return {
				filters: [
					["PageType", "issingle", "=", 0],
					["PageType", "name", "not in", jingrow.model.core_pagetypes_list],
				],
			};
		});

		frm.page.set_primary_action(__("Update"), function () {
			if (!frm.pg.update_value) {
				jingrow.throw(__('Field "value" is mandatory. Please specify value to be updated'));
			} else {
				frm.call("bulk_update").then((r) => {
					let failed = r.message;
					if (!failed) failed = [];

					if (failed.length && !r._server_messages) {
						jingrow.throw(
							__("Cannot update {0}", [
								failed.map((f) => (f.bold ? f.bold() : f)).join(", "),
							])
						);
					} else {
						jingrow.msgprint({
							title: __("Success"),
							message: __("Updated Successfully"),
							indicator: "green",
						});
					}

					jingrow.hide_progress();
					frm.save();
				});
			}
		});
	},

	document_type: function (frm) {
		// set field options
		if (!frm.pg.document_type) return;

		jingrow.model.with_pagetype(frm.pg.document_type, function () {
			var options = $.map(jingrow.get_meta(frm.pg.document_type).fields, function (d) {
				if (d.fieldname && jingrow.model.no_value_type.indexOf(d.fieldtype) === -1) {
					return d.fieldname;
				}
				return null;
			});
			frm.set_df_property("field", "options", options);
		});
	},
});
