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

jingrow.ui.form.on("Dropbox Settings", {
	refresh: function (frm) {
		frm.toggle_display(
			["app_access_key", "app_secret_key"],
			!frm.pg.__onload?.dropbox_setup_via_site_config
		);
		frm.events.take_backup(frm);
	},

	are_keys_present: function (frm) {
		return (
			(frm.pg.app_access_key && frm.pg.app_secret_key) ||
			frm.pg.__onload?.dropbox_setup_via_site_config
		);
	},

	allow_dropbox_access: function (frm) {
		if (!frm.events.are_keys_present(frm)) {
			jingrow.msgprint(__("App Access Key and/or Secret Key are not present."));
			return;
		}

		jingrow.call({
			method: "jingrow.integrations.pagetype.dropbox_settings.dropbox_settings.get_dropbox_authorize_url",
			freeze: true,
			callback: function (r) {
				if (!r.exc) {
					window.open(r.message.auth_url);
				}
			},
		});
	},

	take_backup: function (frm) {
		if (frm.pg.enabled && (frm.pg.dropbox_refresh_token || frm.pg.dropbox_access_token)) {
			frm.add_custom_button(__("Take Backup Now"), function () {
				jingrow.call({
					method: "jingrow.integrations.pagetype.dropbox_settings.dropbox_settings.take_backup",
					freeze: true,
				});
			});
		}
	},
});
