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


import json
from base64 import b64decode

import jingrow
import requests

from jcloud.utils import log_error


def get_context(context):
	code = jingrow.form_dict.code
	state = jingrow.form_dict.state
	redirect_url = jingrow.utils.get_url("/dashboard")
	if code and state:
		decoded_state = json.loads(b64decode(state).decode())
		team = decoded_state["team"]
		redirect_url = jingrow.utils.get_url(decoded_state["url"])
		obtain_access_token(code, team)
		jingrow.db.commit()
	jingrow.flags.redirect_location = redirect_url
	raise jingrow.Redirect

def obtain_access_token(code, team):
	response = None
	try:
		client_id = jingrow.db.get_single_value("Jcloud Settings", "github_app_client_id")
		client_secret = jingrow.db.get_single_value(
			"Jcloud Settings", "github_app_client_secret"
		)
		data = {"client_id": client_id, "client_secret": client_secret, "code": code}
		headers = {"Accept": "application/json"}
		response = requests.post(
			"https://github.com/login/oauth/access_token", data=data, headers=headers
		).json()
		jingrow.db.set_value("Team", team, "github_access_token", response["access_token"])
	except Exception:
		log_error("Access Token Error", team=team, code=code, response=response)

