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

jingrow.ui.form.on("Google Drive", {
	refresh: function (frm) {
		if (!frm.pg.enable) {
			frm.dashboard.set_headline(
				__("To use Google Drive, enable {0}.", [
					`<a href='/app/google-settings'>${__("Google Settings")}</a>`,
				])
			);
		}

		jingrow.realtime.on("upload_to_google_drive", (data) => {
			if (data.progress) {
				const progress_title = __("Uploading to Google Drive");
				frm.dashboard.show_progress(
					progress_title,
					(data.progress / data.total) * 100,
					data.message
				);
				if (data.progress === data.total) {
					frm.dashboard.hide_progress(progress_title);
				}
			}
		});

		if (frm.pg.enable && frm.pg.refresh_token) {
			let sync_button = frm.add_custom_button(__("Take Backup"), function () {
				jingrow.show_alert({
					indicator: "green",
					message: __("Backing up to Google Drive."),
				});
				jingrow
					.call({
						method: "jingrow.integrations.pagetype.google_drive.google_drive.take_backup",
						btn: sync_button,
					})
					.then((r) => {
						jingrow.msgprint(r.message);
					});
			});
		}

		if (frm.pg.enable && frm.pg.backup_folder_name && !frm.pg.refresh_token) {
			frm.dashboard.set_headline(
				__(
					"Click on <b>Authorize Google Drive Access</b> to authorize Google Drive Access."
				)
			);
		}

		if (frm.pg.enable && frm.pg.refresh_token && frm.pg.authorization_code) {
			frm.page.set_indicator("Authorized", "green");
		}
	},
	authorize_google_drive_access: function (frm) {
		jingrow.call({
			method: "jingrow.integrations.pagetype.google_drive.google_drive.authorize_access",
			args: {
				reauthorize: frm.pg.authorization_code ? 1 : 0,
			},
			callback: function (r) {
				if (!r.exc) {
					frm.save();
					window.open(r.message.url);
				}
			},
		});
	},
});
