extends Control

var ca_request
var auth_request
var toot_request

# Called when the node enters the scene tree for the first time.
func _ready():
	Globals.loadConfig()
	if len(Globals.providers.mastodon) > 0:
		if Globals.providers.mastodon[0].has("baseURL"):
			print("Setting base url")
			$VBoxContainer/HBoxContainer/TextEdit.text = Globals.providers.mastodon[0].baseURL
		if Globals.providers.mastodon[0].has("oauth_token"):
			print("Already Registered")
			$VBoxContainer/AuthUser.disabled = true

# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass

func _on_Login_pressed():
	if len(Globals.providers.mastodon) == 0:
		Globals.providers.mastodon = {}
	if !Globals.providers.mastodon[0].has("app_client_id"):
		register_app()
	if !Globals.providers.mastodon[0].has("oauth_token"):
		auth_user()

func register_app():
	var headers = ["Content-Type: application/json"]
	var data = {
		"client_name": "ASingCrow",
		"redirect_uris": "urn:ietf:wg:oauth:2.0:oob",
		"scopes": "read write follow push",
		"website": "https://asingcrow.martyn.berlin"
	}
	ca_request = HTTPRequest.new()
	add_child(ca_request)
	ca_request.connect("request_completed",self,"_on_app_created")
	ca_request.request("https://toot.martyn.berlin/api/v1/apps",headers,true,HTTPClient.METHOD_POST,JSON.print(data))

func _on_app_created(result, response_code, headers, body):
	print("Response...")
	if response_code != 200:
		print("PANIC! got "+String(response_code))
		print(body.get_string_from_utf8)
		return
	var response = parse_json(body.get_string_from_utf8())
	var dict = {
		"app_client_id": response.client_id,
		"app_client_secret": response.client_secret }
	Globals.providers.mastodon.append(dict)
	Globals.saveConfig()
	remove_child(ca_request)

func _on_token_requested(result, response_code, headers, body):
	print("Response...")
	if response_code != 200:
		print("PANIC! got "+String(response_code))
		print(body.get_string_from_utf8())
		return
	var response = parse_json(body.get_string_from_utf8())
	Globals.providers.mastodon[0].oauth_token = response.access_token
	Globals.saveConfig()
	remove_child(auth_request)
	pass

func _on_Button3_pressed():
	var client = Globals.providers.mastodon
	var headers = ["Content-Type: application/json",
		"Authorization: Bearer "+client[0].oauth_token]
	var data = {
		"status": "Test toot",
	}
	toot_request = HTTPRequest.new()
	add_child(toot_request)
	toot_request.connect("request_completed",self,"_on_tooted")
	toot_request.request("https://toot.martyn.berlin/api/v1/statuses",headers,true,HTTPClient.METHOD_POST,JSON.print(data))
	print("Headers: ")
	print(headers)
	print("Sending...")
	print(JSON.print(data))
	
func _on_tooted(result, response_code, headers, body):
	if response_code != 200:
		print("PANIC! got "+String(response_code))
		print(body.get_string_from_utf8())
		return
	var response = parse_json(body.get_string_from_utf8())
	print("Tooted successfully!")
	print(body)
	remove_child(toot_request)

func auth_user():
	var client = Globals.providers.mastodon
	OS.shell_open("https://toot.martyn.berlin/oauth/authorize?client_id="+client[0].app_client_id+"&scope=read+write+follow+push&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code")
	$VBoxContainer/CodeEntry.visible=true


func _on_CodeEntry_on_authorize(code):
	var client = Globals.providers.mastodon
	var headers = ["Content-Type: application/json"]
	var data = {
		"client_id": client[0].app_client_id,
		"client_secret": client[0].app_client_secret,
		"redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
		"grant_type": "authorization_code",
		"scope": "read write follow push",
		"code": code
	}
	auth_request = HTTPRequest.new()
	add_child(auth_request)
	auth_request.connect("request_completed",self,"_on_token_requested")
	auth_request.request("https://toot.martyn.berlin/oauth/token",headers,true,HTTPClient.METHOD_POST,JSON.print(data))
	pass # Replace with function body.


func _on_TextEdit_text_changed(new_text):
	var dict
	if len(Globals.providers.mastodon) > 0:
		dict = Globals.providers.mastodon[0]
	else:
		dict = {}
		Globals.providers.mastodon[0] = dict
	Globals.providers.mastodon[0].baseURL = $VBoxContainer/HBoxContainer/TextEdit.text
	Globals.saveConfig()
