// Copyright (c) 2015, JINGROW and Contributors
// MIT License. See license.txt
jingrow.provide("jingrow.desk");

jingrow.ui.form.on("Event", {
	onload: function (frm) {
		frm.set_query("reference_pagetype", "event_participants", function () {
			return {
				filters: {
					issingle: 0,
				},
			};
		});
		frm.set_query("google_calendar", function () {
			return {
				filters: {
					owner: jingrow.session.user,
				},
			};
		});
	},
	refresh: function (frm) {
		if (frm.pg.event_participants) {
			frm.pg.event_participants.forEach((value) => {
				frm.add_custom_button(
					__(value.reference_pagename),
					function () {
						jingrow.set_route("Form", value.reference_pagetype, value.reference_pagename);
					},
					__("Participants")
				);
			});
		}

		frm.page.set_inner_btn_group_as_primary(__("Add Participants"));

		frm.add_custom_button(
			__("Add Contacts"),
			function () {
				new jingrow.desk.eventParticipants(frm, "Contact");
			},
			__("Add Participants")
		);

		const [ends_on_date] = frm.pg.ends_on
			? frm.pg.ends_on.split(" ")
			: frm.pg.starts_on?.split(" ") || [];

		if (
			ends_on_date &&
			frm.pg.google_meet_link &&
			jingrow.datetime.now_date() <= ends_on_date
		) {
			frm.dashboard.set_headline(
				__("Join video conference with {0}", [
					`<a target='_blank' href='${frm.pg.google_meet_link}'>Google Meet</a>`,
				])
			);
		}
	},
	repeat_on: function (frm) {
		if (frm.pg.repeat_on === "Every Day") {
			["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].map(
				function (v) {
					frm.set_value(v, 1);
				}
			);
		}
	},
});

jingrow.ui.form.on("Event Participants", {
	event_participants_remove: function (frm, cdt, cdn) {
		if (cdt && !cdn.includes("new-event-participants")) {
			jingrow.call({
				type: "POST",
				method: "jingrow.desk.pagetype.event.event.delete_communication",
				args: {
					event: frm.pg,
					reference_pagetype: cdt,
					reference_pagename: cdn,
				},
				freeze: true,
				callback: function (r) {
					if (r.exc) {
						jingrow.show_alert({
							message: __("{0}", [r.exc]),
							indicator: "orange",
						});
					}
				},
			});
		}
	},
});

jingrow.desk.eventParticipants = class eventParticipants {
	constructor(frm, pagetype) {
		this.frm = frm;
		this.pagetype = pagetype;
		this.make();
	}

	make() {
		let me = this;

		let table = me.frm.get_field("event_participants").grid;
		new jingrow.ui.form.LinkSelector({
			pagetype: me.pagetype,
			dynamic_link_field: "reference_pagetype",
			dynamic_link_reference: me.pagetype,
			fieldname: "reference_pagename",
			target: table,
			txt: "",
		});
	}
};
