#
# Copyright (C) 2018  Sage Vaillancourt, sagev9000@gmail.com
#
# This file is part of Fronter.
# 
# Fronter is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# Fronter is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with Fronter.  If not, see <http://www.gnu.org/licenses/>.
#

extends Node

signal player_info
signal start_multiplayer_game

var my_ip
var peer
var player_info = {}
var incoming_name
var my_info = { name = "", color = "FFFFFF" }
var server_ip

var test_id

func _ready():
	my_ip = IP.get_local_addresses()[1]
	prints(my_ip)
	get_tree().connect("network_peer_connected", self, "_player_connected")
	get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
	get_tree().connect("connected_to_server", self, "_connected_ok")
	get_tree().connect("connection_failed", self, "_connected_fail")
	get_tree().connect("server_disconnected", self, "_server_disconnected")
	get_tree().paused = true
	$ServerIP.text = str(my_ip)
	#$UsernamePage/UsernameEntry.text = my_info.name

func _on_Server_pressed():
	peer = NetworkedMultiplayerENet.new()
	peer.create_server(6969, 8)
	get_tree().set_network_peer(peer)
	get_tree().set_meta("network_peer", peer)
	prints(get_tree().is_network_server())
	prints(get_tree().has_network_peer())
	prints(my_info)
	$ServerIP.visible = true
	$ServerIP.text = str(my_ip)
	$EnterIP.visible = false
	$ServerEntry.visible = false
	$ServerAcceptIcon.visible = false
	$ConnectTo.visible = true
	$StartServer.visible = false
	$Server.visible = false
	player_info[get_tree().get_network_unique_id()] = my_info
	$StartGame.visible = true

func _on_Client_pressed():
	server_ip = $ServerEntry.text
	peer = NetworkedMultiplayerENet.new()
	peer.create_client(server_ip, 6969)
	get_tree().set_network_peer(peer)
	get_tree().set_meta("network_peer", peer)
	prints(get_tree().is_network_server())
	prints(get_tree().has_network_peer())
	
func _player_connected(id):
	prints("AYYYYYYYYY ", id)
	test_id = id
	
func _player_disconnected(id):
	prints("OH NO ", id)
	player_info.erase(id) # Erase player from info
	
func _connected_ok():
    # Only called on clients, not server. Send my ID and info to all the other peers
	rpc("register_player", get_tree().get_network_unique_id(), my_info)
	$ServerAcceptIcon.visible = false
	$EnterIP.visible = false
	$ConnectTo.visible = false
	$StartServer.visible = false
	$Server.visible = false
	$ServerEntry.visible = false

func _server_disconnected():
    pass # Server kicked us, show error and abort

func _connected_fail():
    pass # Could not even connect to server, abort

remote func register_player(id, info):
	player_info[id] = info 
	if get_tree().is_network_server():
		# Send my info to new player
		#rpc_id(id, "register_player", 1, my_info)
		# Send the info of existing players
		for peer_id in player_info:
			rpc_id(id, "register_player", peer_id, player_info[peer_id])
	emit_signal("player_info", id, player_info)

	$Lobby/RichTextLabel.bbcode_text = ""
		#$Players.text = str(player_info)
	for p in player_info:
		$Lobby/RichTextLabel.append_bbcode(str("[color=#", player_info[p].color, "]", player_info[p].name, "[/color]\n"))

    # Call function to update lobby UI here ^^^^^

func setName(newname):
	$UsernamePage/UsernameEntry.text = newname

#remote func change_color(id, color):
#	player_info[id].color = color
#	if get_tree().is_network_server():
#		rpc("change_color", id, color)
#	emit_signal("player_info", id, player_info)

func _on_Name_pressed():
	my_info = { name = $LineEdit.text }

func _on_LineEdit_text_entered(new_text):
	usernameEntered()

func _on_Server_Entry_text_entered(new_text):
	#server_ip = new_text
	_on_Client_pressed()

func _on_BackToMain_pressed():
	$Server.visible = false
	$Client.visible = false
	$Name.visible = false
	$UsernamePage/UsernameEntry.visible = false
	$ServerEntry.visible = false
	$UsernameLabel.visible = false
	$BackToMain.visible = false
	$ColorRect.visible = false
	$UsernamePage/UsernameAccept.visible = false
	$UsernamePage/UsernameAcceptIcon.visible = false
	$BackIcon.visible = false
	$UsernamePage/EnterUsername.visible = false
	$StartServer.visible = false
	$ServerAcceptIcon.visible = false
	$EnterIP.visible = false
	$ConnectTo.visible = false
	$UsernameLabel.visible = false
	$Lobby/RichTextLabel.visible = false

func _on_UsernameEntry_text_changed(new_text):
	my_info = {name = new_text, color = my_info.color}

func _on_UsernameAccept_pressed():
	usernameEntered()
	
func usernameEntered():
	my_info = {name = $UsernamePage/UsernameEntry.text, color = my_info.color}
	$UsernameLabel.text = str("Your netname is \"", $UsernamePage/UsernameEntry.text, "\"")
	if $UsernamePage/UsernameEntry.text > "":
		$UsernamePage/UsernameEntry.visible = false
		$UsernamePage/UsernameAccept.visible = false
		$UsernamePage/UsernameAcceptIcon.visible = false
		$UsernamePage/EnterUsername.visible = false
		prints(my_info)
		$StartServer.visible = true
		$EnterIP.visible = true
		$ServerEntry.visible = true
		$Server.visible = true
		$ServerAcceptIcon.visible = true
		$Client.visible = true

func startGame():
	rpc("yeeper")

sync func yeeper():
	$BackToMain.visible = false
	$BackIcon.visible = false
	_on_BackToMain_pressed()
	emit_signal("start_multiplayer_game")
	$StartGame.visible = false