extends Control

# 601 LOC 11/9 - 2023
# 628 LOC 15/9 - 2023
# 631 LOC 16/9 - 2023
# 554 LOC 30/5 - 2024
# 551 LOC 3/6 - 2024
# 386 LOC 12/6 - 2024

##TODO
# 15. Fix for local play

@onready
var open_button: Button = $Open

@onready
var fileDialog: FileDialog = $FileDialog

@onready
var inspiration_scroll: ScrollContainer = $ScrollContainer

@onready
var inspiration_list: VBoxContainer = $ScrollContainer/VBoxContainer

@onready
var game_label: Label = $VBoxContainer/GameLabel

@onready
var song_label: Label = $VBoxContainer/SongLabel

@onready
var add_player_container: HBoxContainer = $Players/VBoxContainer/AddPlayerContainer

@onready
var add_players_button: TextureButton = $Players/VBoxContainer/HBoxContainer/AddPlayersButton

@onready
var add_player_button: Button = $Players/VBoxContainer/AddPlayerContainer/AddPlayerButton

@onready
var new_player_name_field: TextEdit = $Players/VBoxContainer/AddPlayerContainer/PlayerNameField

@onready
var reset_playlist_button: Button = $ResetPlaylistButton

@onready
var reset_points_button: Button = $ResetPointsButton

@onready
var sound_test_button: Button = $SoundTestButton

@onready
var sync_button: Button = $SyncButton

@onready
var sync_window: Control = %SyncWindow

@onready
var settings_button: Button = $SettingsButton

@onready
var settings_window: Control = $SettingsWindow

@onready
var statistics_button: Button = $StatisticsButton

@onready
var statistic_popup: PopupPanel = $StatisticsPopupPanel

@onready
var statistic_label: Label = $StatisticsPopupPanel/StatisticsLabel

@onready
var about_button: Button = $AboutButton

@onready
var about_popup: PopupPanel = $AboutPopupPanel

@onready
var show_answer_button: Button = $ShowAnswerButton

@onready
var next_button: Button = $NextButton

@onready
var music_list_scroll: ScrollContainer = $MusicListPanel/ScrollContainer

@onready
var music_list: VBoxContainer = $MusicListPanel/ScrollContainer/MusicList

@onready
var player_container: VBoxContainer = $Players/VBoxContainer

@onready
var character_select: Control = $CharacterSelect

@onready
var new_character_select: Control = %NewCharacterSelect

@onready
var search_button: Button = $SearchButton

@onready
var search_view: Control= $Search

@onready
var version_label: Label = $AboutPopupPanel/VBoxContainer/VersionLabel

@onready
var whats_new_label: Label = $AboutPopupPanel/VBoxContainer/HBoxContainer/NewLabel

@onready
var shortcut_label: Label = $AboutPopupPanel/VBoxContainer/HBoxContainer/ShortcutsLabel

@onready
var coming_label: Label = $AboutPopupPanel/VBoxContainer/HBoxContainer/CommingLabel

@onready
var winner_popup: PopupPanel = $WinnerPopupPanel

@onready
var winner_label: Label = %WinnerLabel

@onready
var winner_picture: TextureRect = %WinnerPicture

@onready
var auto_repeat_song_button: CheckButton = $RepeatSongCheckButton

@onready
var music_player_container: PanelContainer = $MusicPlayer

@onready
var log: Control = %Log

@onready
var debug_label: Label = $DebugLabel

var player: PackedScene = preload("res://Player.tscn")
var song_list_object: PackedScene = preload("res://song_list_object.tscn")

var songs: Array= []
var games: Array = []
var current_player: Node

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	var debug: bool = OS.has_feature("debug")
	var is_mac: bool = OS.has_feature("macos")
	if debug:
		print("is_debug")
		debug_label.visible = true
		Settings.is_debug = true
		Settings.default_path = "http://localhost:8080"
		Settings.selected_server = 3
		Settings.winning_score = 5
	if is_mac:
		print("is_mac")
	next_button.pressed.connect(play_next_song)
	show_answer_button.pressed.connect(show_answer_pressed)
	search_button.pressed.connect(show_search)
	sync_button.pressed.connect(sync_games)
	sound_test_button.pressed.connect(music_player_container.get_sound_test_song)
	statistics_button.pressed.connect(get_statistics)
	about_button.pressed.connect(show_about)
	settings_button.pressed.connect(show_settings)
	reset_playlist_button.pressed.connect(reset_playlist)
	reset_points_button.pressed.connect(reset_points)
	
	character_select.connect("character_selected", _on_character_selected)
	new_character_select.connect("new_new_character_selected", _on_new_character_selected)
	new_player_name_field.connect("enter_key_pressed", add_player)
	music_player_container.connect("play_next_song", play_next_song)
	music_player_container.connect("update_song_list", update_song_list)
	settings_window.connect("server_changed", server_updated)
	sync_window.connect("sync_started", _on_sync_started)
	sync_window.connect("sync_finished", _on_sync_finished)
	
	
	add_players_button.pressed.connect(add_players)
	add_player_button.pressed.connect(add_player)
	open_button.pressed.connect(open)
	auto_repeat_song_button.pressed.connect(repeat_song)
	
	get_suggestion_list()
	fetch_song_list_at_start()
	fetch_song()
	search_view.get_list_of_games()
	new_character_select.load_characters()
	
func _input(event: InputEvent) -> void:
	if event is InputEventKey and event.pressed:
		if event.alt_pressed && event.keycode == KEY_UP:
			print("Alt + UP pressed")
			music_player_container.change_volume(0.05)
		if event.alt_pressed && event.keycode == KEY_DOWN:
			print("Alt + DOWN pressed")
			music_player_container.change_volume(-0.05)
		if event.alt_pressed && event.ctrl_pressed && event.keycode == KEY_LEFT:
			print("Ctrl + Alt + LEFT pressed")
			music_player_container.restart()
		elif event.alt_pressed && event.keycode == KEY_LEFT:
			print("Alt + LEFT pressed")
			music_player_container.seek(-5)
		if event.alt_pressed && event.keycode == KEY_RIGHT:
			print("Alt + RIGHT pressed")
			music_player_container.seek(5)
		if event.alt_pressed && event.keycode == KEY_ENTER:
			print("Alt + Enter pressed")
			Settings.fullscreen = !Settings.fullscreen
			settings_window.fullscreen_button.button_pressed = Settings.fullscreen
			if Settings.fullscreen == true:
				DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)
			if Settings.fullscreen == false:
				DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_WINDOWED)
		if event.alt_pressed && event.keycode == KEY_L:
			log.visible = !log.visible

func server_updated() -> void:
	print("server_updated")
	update_from_server()
	reset_points()
	
func update_from_server() -> void:
	print("update_from_server")
	search_view.get_list_of_games()
	get_suggestion_list()
	reset_playlist()
	new_character_select.load_characters()

func repeat_song() -> void:
	Settings.auto_repeat_song = !Settings.auto_repeat_song

func show_answer_pressed() -> void:
	print("show_answer_pressed")
	Playlist.song_is_answered()
	update_song_list()

func fetch_song_list_at_start() -> void:
	print("fetch_song_list_at_start")
	var fetch_song_list_at_start_done: Callable = func fetch_songs_at_start_done(data) -> void:
		Playlist.clear_song_list()
		if data == null:
			Playlist.update_last_played_song()
			update_song_list()
			return
		if typeof(data) == TYPE_ARRAY:
			for d: Dictionary in data:
				var new_song_object: SongObject = SongObject.new()
				new_song_object.song_number = d.SongNo
				new_song_object.game_title = d.Game
				new_song_object.song_title = d.Song
				new_song_object.is_answered = true
				new_song_object.has_played = true
				Playlist.add_to_playlist(new_song_object)
		else:
			print("Unexpected data")
		Playlist.update_last_played_song()
		update_song_list()
	Settings.make_request2("/music/list", fetch_song_list_at_start_done, true)

func play_next_song() -> void:
	print("play_next_song ", Playlist.latest_played_song)
	if Playlist.first_song_played:
		Playlist.set_latest_played_song()
	Playlist.first_song_played = true
	music_player_container.play_song_object(Playlist.latest_played_song)
	if !(Playlist.get_preloaded_songs() > 0):
		next_button.disabled = true
	if !Playlist.is_song_downloading:
		fetch_song()

#not first "/music/addPlayed"
#"/music/rand"
#"/music/addQue"
#"/music/info"
func fetch_song() -> void:
	print("fetch_song")
	Playlist.is_song_downloading = true
	var url: String = ""
	if Settings.use_low_played_mode:
		url = "/music/rand/low"
	else:
		url = "/music/rand"
	var new_song_object: SongObject = SongObject.new()
	var fetch_song_done: Callable = func fetch_song_done(body: PackedByteArray) -> void:
		print("fetch_song_done")
		var sound: AudioStream = AudioStreamMP3.new()
		sound.data = body
		new_song_object.song = sound
		
		var added_to_que_done: Callable = func added_to_que_done() -> void:
			print("added_to_que_done")
			var fetch_song_info_done: Callable = func fetch_song_info_done(data_received: Dictionary) -> void:
				print("fetch_song_info_done")
				new_song_object.song_number = data_received.SongNo
				new_song_object.game_title = data_received.Game
				new_song_object.song_title = data_received.Song
			
				print("new_song_object: ", new_song_object.to_string())
				Playlist.add_to_playlist(new_song_object)
				next_button.disabled = false
				if Playlist.should_preload_more_songs():
					fetch_song()
				else:
					Playlist.is_song_downloading = false
				if Settings.is_debug:
					update_song_list()
			Settings.make_request2("/music/info", fetch_song_info_done, true)

		Settings.make_request2("/music/addQue", added_to_que_done, false)

	Settings.make_request2(url, fetch_song_done, true)
	
func update_song_list() -> void:
	print("update_song_list")
	if Playlist.currently_playing_song >= 0:
		game_label.text = Playlist.get_current_game_title()
		song_label.text = Playlist.get_current_song_title()
	Settings.delete_children(music_list)
	for s: SongObject in Playlist.get_playlist():
		var new_song_list_object: SongListObject = song_list_object.instantiate()
		new_song_list_object.song_object = s
		new_song_list_object.gui_input.connect(song_object_clicked.bind(s.song_number))
		music_list.add_child(new_song_list_object)

func song_object_clicked(event: InputEvent, song_no: int) -> void:
	if (event is InputEventMouseButton && event.pressed && event.button_index == MOUSE_BUTTON_LEFT):
		print("Clicked Song Object: ", Playlist.song_object_array[song_no].to_string())
		if Settings.character_select_open == false:
			if Playlist.get_song(song_no) == null:
				print("has no song, need to download")
				var song_downloaded: Callable = func song_downloaded(body: PackedByteArray) -> void:
					var sound: AudioStream = AudioStreamMP3.new()
					sound.data = body
					Playlist.add_song_to_song_object(song_no, sound)
					music_player_container.play_song_object(song_no)
				Settings.make_request2("/music?song=" + str(song_no), song_downloaded, true)
			else:
				print("song already downloaded")
				music_player_container.play_song_object(song_no)

func reset_playlist() -> void:
	print("reset_playlist")
	var playlist_reset_done: Callable = func playlist_reset_done() -> void:
		Playlist.reset_playlist()
		fetch_song_list_at_start()
		fetch_song()
		
	Settings.make_request2("/music/reset", playlist_reset_done, false)

func reset_points() -> void:
	print("reset_points")
	for player_objects: PlayerObject in Settings.player_array:
		player_objects.reset_points()
	load_players()

func show_about() -> void:
	print("show_about")
	about_popup.visible = true
	version_label.text = Settings.version
	whats_new_label.text = Settings.whats_new
	shortcut_label.text = Settings.shortcuts
	coming_label.text = Settings.whats_left
	
func show_settings() -> void:
	print("show_settings")
	settings_window.visible = true
	
func get_statistics() -> void:
	print("get_statistics")
	statistic_popup.visible = true
	statistic_label.text = "Total amount of games in the playlist: " + str(games.size())
	
func sync_games() -> void:
	print("sync_games")
	sync_window.start_sync()

func _on_sync_started() -> void:
	print("_on_sync_started")
	sync_button.disabled = false
	sound_test_button.disabled = true
	reset_playlist_button.disabled = true
	show_answer_button.disabled = true
	next_button.disabled = true

func _on_sync_finished() -> void:
	print("_on_sync_finished")
	update_from_server()
	sound_test_button.disabled = false
	reset_playlist_button.disabled = false
	show_answer_button.disabled = false

func get_suggestion_list() -> void:
	print("get_suggestion_list")
	var populate_list: Callable = func populate_list(array) -> void:
		if typeof(array) == TYPE_ARRAY:
			games = []
			Settings.delete_children(inspiration_list)
			games.append_array(array)
			for game: String in games:
				var inspiration_label: Label = Label.new()
				inspiration_label.set_texture_filter(TextureFilter.TEXTURE_FILTER_NEAREST)
				inspiration_label.add_theme_font_size_override("font_size", 20)
				inspiration_label.text = game
				inspiration_label.autowrap_mode = TextServer.AUTOWRAP_WORD
				inspiration_list.add_child(inspiration_label)
			inspiration_scroll.scroll_to_bottom()
		else:
			print("Unexpected data")
	Settings.make_request2("/music/all", populate_list, true)

func add_players() -> void:
	print("add_players")
	Settings.edit_players = !Settings.edit_players
	add_player_container.visible = !add_player_container.visible
	new_player_name_field.grab_focus()

func add_player() -> void:
	print("add_player")
	if new_player_name_field.text != "":
		var new_player_object: PlayerObject = PlayerObject.new(new_player_name_field.text, Settings.player_array.size())
		new_player_name_field.text = ""
		Settings.player_array.append(new_player_object)
		new_player_object.connect("first_point_triggerd", music_player_container._on_point_triggered.bind("first"))
		new_player_object.connect("match_point_triggerd", music_player_container._on_point_triggered.bind("match"))
		new_player_object.connect("winner_triggerd", _on_player_won.bind(new_player_object.id))
		new_player_object.connect("point_given_sound", _on_make_point_given_sound)
		new_player_object.connect("player_point_given", _on_point_given.bind(new_player_object.id))
		new_player_object.connect("player_point_taken", _on_point_taken.bind(new_player_object.id))
		load_players()

func load_players() -> void:
	print("load_players")
	Settings.delete_player_children(player_container)
	var counter: int = 0
	for player_object: PlayerObject in Settings.player_array:
		print(player_object.player_name)
		
		var new_player: Player = player.instantiate()
		new_player.id = counter
		
		new_player.connect("change_character_clicked", _on_player_change_character_clicked.bind(new_player))
		new_player.connect("player_removed", _on_player_removed.bind(counter))

		player_container.add_child(new_player)
		counter += 1

func _on_point_given(player_given_point: int) -> void:
	print("_on_point_given")
	log.add_log_row(Settings.player_array[player_given_point].player_name + " got a point")
	if Playlist.currently_playing_song >= 0:
		Playlist.add_point(player_given_point)
	update_song_list()

func _on_make_point_given_sound() -> void:
	music_player_container.play_sound_effect(preload("res://sounds/itemopen.wav"))

func _on_point_taken(player_taken_point: int) -> void:
	print("_on_point_taken")
	log.add_log_row(Settings.player_array[player_taken_point].player_name + " lost a point")
	music_player_container.play_sound_effect(preload("res://sounds/itemequip.wav"))
	if Playlist.currently_playing_song >= 0:
		Playlist.remove_point(player_taken_point)
	update_song_list()

func _on_player_won(winning_player_id: int) -> void:
	print("_on_player_won")
	winner_popup.visible = true
	winner_label.text = Settings.player_array[winning_player_id].player_name + " won!!"
	winner_picture.custom_minimum_size = Vector2(692, 300)
	winner_picture.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	winner_picture.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	winner_picture.texture = Settings.player_array[winning_player_id].character
	music_player_container.play_sound(preload("res://sounds/winning.mp3"))
	Settings.add_to_stats = false

func _on_player_removed(player_to_remove: int) -> void:
	print("_on_player_removed ", player_to_remove)
	Settings.player_array.remove_at(player_to_remove)
	load_players()
	Playlist.remove_player_from_list(player_to_remove)
	update_song_list()

func _on_player_change_character_clicked(new_player: Node) -> void:
	print("_on_player_change_character_clicked")
	current_player = new_player
	new_character_select.show_grid()

func _on_character_selected(file_name: String) -> void:
	print("_on_character_selected")
	character_select.visible = false
	current_player.character_selected(file_name)

func _on_new_character_selected(character_texture: ImageTexture) -> void:
	print("_on_new_character_selected")
	current_player.new_character_selected(character_texture)

func show_search() -> void:
	print("show_search")
	if search_view.visible == false:
		search_view.visible = true
	else:
		search_view.visible = false


###Local

var local_path: String = '/Users/sebastian/ResilioSync/Sorterat_test/Metal Gear Solid 4 - Guns of the Patriots/2-16 Metal Gear Saga.mp3'

func open() -> void:
	fileDialog.popup()
	
func _on_file_dialog_dir_selected(path: String) -> void:
	print(path)
	dir_contents(path)
	
func dir_contents(path: String) -> void:
	var dir: DirAccess = DirAccess.open(path)
	if dir:
		dir.list_dir_begin()
		var file_name: String = dir.get_next()
		songs.clear()
		games = []
		while file_name != "":
			if dir.current_is_dir():
				#print("Found directory: " + file_name)
				games.append(file_name)
			else:
				#print("Found file: " + file_name)
				if file_name.ends_with(".mp3"):
					songs.append(path + "/" + file_name)
			file_name = dir.get_next()
	else:
		print("An error occurred when trying to access the path.")

	for game: String in games:
		var local_inspiration_label: Label = Label.new()
		local_inspiration_label.text = game
		inspiration_list.add_child(local_inspiration_label)
