# Copyright (c) 2020, JINGROW
# For license information, please see license.txt


import jingrow
import requests

from jcloud.utils import log_error


def get_context(context):
	if not jingrow.db.get_single_value("Jcloud Settings", "github_app_id"):
		code = jingrow.form_dict.code
		response = None
		try:
			headers = {"Accept": "application/vnd.github.v3+json"}
			response = jingrow._dict(
				requests.post(
					f"http://git.jingrow.com/api/v1/app-manifests/{code}/conversions", headers=headers
				).json()
			)

			settings = jingrow.get_pg("Jcloud Settings", "Jcloud Settings")
			settings.github_app_id = response.id
			settings.github_app_client_id = response.client_id
			settings.github_app_client_secret = response.client_secret
			settings.github_app_public_link = response.html_url
			settings.github_app_private_key = response.pem
			settings.github_webhook_secret = response.webhook_secret
			settings.save()
			jingrow.db.commit()
		except Exception:
			log_error("GitHub App Creation Error", code=code, response=response)

	redirect_url = jingrow.utils.get_url("/app#Form/Jcloud Settings")
	jingrow.flags.redirect_location = redirect_url
	raise jingrow.Redirect
