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

jingrow.ui.form.on("Connected App", {
	refresh: (frm) => {
		frm.add_custom_button(__("Get OpenID Configuration"), async () => {
			if (!frm.pg.openid_configuration) {
				jingrow.msgprint(__("Please enter OpenID Configuration URL"));
			} else {
				try {
					const response = await fetch(frm.pg.openid_configuration);
					const oidc = await response.json();
					frm.set_value("authorization_uri", oidc.authorization_endpoint);
					frm.set_value("token_uri", oidc.token_endpoint);
					frm.set_value("userinfo_uri", oidc.userinfo_endpoint);
					frm.set_value("introspection_uri", oidc.introspection_endpoint);
					frm.set_value("revocation_uri", oidc.revocation_endpoint);
				} catch (error) {
					jingrow.msgprint(__("Please check OpenID Configuration URL"));
				}
			}
		});

		if (!frm.is_new()) {
			frm.add_custom_button(__("Connect to {}", [frm.pg.provider_name]), async () => {
				jingrow.call({
					method: "initiate_web_application_flow",
					pg: frm.pg,
					callback: function (r) {
						window.open(r.message, "_blank");
					},
				});
			});
		}

		frm.toggle_display("sb_client_credentials_section", !frm.is_new());
	},
});
