extends MarginContainer

const grid_space = preload("res://GridSpace.tscn")
const grid_entry = preload("res://Entry.tscn")
const title_label = preload("res://TitleLabel.tscn")

const max_entry_size = 100

var current_entries = 0
var free_space = 0

var gridsize = 5
var usefreespace = true

var title_name = {2: "BN", 3: "BIN", 4: "BNGO", 5: "BINGO", 6: "BINGON", 7: "BINGOGO", 8: "BINGOING", 9: "BINGOINGOGOGO"}

var title_color = Color(1, 1, 1)
var text_color = Color(0, 0, 0)
var grid_color = Color(0.671875, 0.671875, 0.671875)


onready var maingrid : Node = $"Main/GridContainer/Main Grid"
onready var titlearray : Node = $"Main/GridContainer/TitleArray"


func _ready():
	set_grid(int($Main/Options/GridSize/LineEdit.text))
	
func _process(delta):
	update_colors()
	
	self.set_size(Vector2(self.rect_size.x, OS.get_window_size().x/2+15), true)
	
	current_entries = $Main/Entries/EntryNav/EntryGrid.get_child_count()
	
	usefreespace = $Main/Options/FreeSpace/CheckBox.pressed
	
	$Main/Entries/EntryNum.text = "There are "+str(current_entries)+"/"+str(max_entry_size)+" entries"
	
	if current_entries < gridsize*gridsize:
		$Main/Entries/Label.visible = true
		$Main/Entries/Label.text = "Not enough entries! For a complete grid, there needs to be at least "+str((gridsize*gridsize)-current_entries)+" more!"
	else:
		$Main/Entries/Label.visible = false
	
	update_grid_text()
	
	
func set_grid(size):
	
	gridsize = size
	if size > 8: size = 8
	if size < 2: size = 2
	maingrid.columns = size
	
	
	for child in titlearray.get_children():
		child.queue_free()
		
	for letter in title_name[size]:
		var newletter = title_label.instance()
		newletter.text = letter
		titlearray.add_child(newletter)
	
	for child in maingrid.get_children():
		child.queue_free()
	for i in (size*size):
		var new_grid = grid_space.instance()
		maingrid.add_child(new_grid)
		print("new cell made!")
	free_space = ceil((size*size)/2)


func _on_LineEdit_text_changed(new_text):
	if new_text != "":
		set_grid(int(new_text))


func _on_LineEdit_focus_exited():
	if int($Main/Options/GridSize/LineEdit.text) < 2: $Main/Options/GridSize/LineEdit.text = "2"
	if int($Main/Options/GridSize/LineEdit.text) > 8: $Main/Options/GridSize/LineEdit.text = "8"


func _on_NewEntry_pressed():
	var entries_to_make = int($Main/Entries/EntryNew/LineEdit.text)
	
	entries_to_make = clamp(entries_to_make, 1, 5)
	
	$Main/Entries/EntryNew/LineEdit.text = str(entries_to_make)
	
	if (current_entries+entries_to_make) > max_entry_size:
		entries_to_make = max_entry_size-current_entries
	
	for i in int(entries_to_make):
		var new_entry = grid_entry.instance()
		$Main/Entries/EntryNav/EntryGrid.add_child(new_entry)
		
		
func get_entries(amount=max_entry_size+1):
	var repeat_times = amount
	var all_entries : Array
	
	for entry in $Main/Entries/EntryNav/EntryGrid.get_children():
		var to_add = entry.return_value()
		if to_add == "": to_add = "Blank"
		all_entries.append(to_add)
		repeat_times -= 1
		if repeat_times <= 0:
			break
		
	return all_entries
	
func update_grid_text():
	var gridupdate = get_entries(gridsize*gridsize)
	var gridpos = 0
	
	var use_free = usefreespace
	
	if len(gridupdate) == 0:
		return "No entries!"
	
	for grid in maingrid.get_children():
		grid.text_set("")
	
	for grid in maingrid.get_children():
		if use_free and gridpos==free_space:
			grid.text_set("Free Space")
			if len(gridupdate)-1 > gridpos:
				gridpos += 1
			else:
				break
			continue
		grid.text_set(gridupdate[gridpos])
		if len(gridupdate)-1 > gridpos:
			gridpos += 1
		else:
			break
			
			

func shuffle_entries():
	for i in 5:
		var all_entries = get_entries()
		all_entries.shuffle()
		var ii = 0
		
		if len(all_entries) <= 0:
			return "List too small"
		
		for entry in $Main/Entries/EntryNav/EntryGrid.get_children():
			entry.set_text(all_entries[ii])
			ii += 1

	
func save_list():
	var data = ""
	data += "gridsize: "+str(gridsize)
	data += "\nusefreespace: "+str(usefreespace)
	data += "\nentries: "+str(get_entries())
	data += "\ntitlecolor: "+str(title_color)
	data += "\ntextcolor: "+str(text_color)
	data += "\ngridcolor: "+str(grid_color)
	data += "\ntextsize: "+str($Main/Options/TextSize/TSizeEdit.text)
	
	#print(data)
	
	$FileDialog.window_title = "Save your list"
	$FileDialog.mode = FileDialog.MODE_SAVE_FILE
	
	$FileDialog.popup()
	
	var savefile = yield(get_node("FileDialog"),"file_selected")

	var save_game = File.new()
	save_game.open(savefile, File.WRITE)
	save_game.store_line(data)
	save_game.close()
	print("List Saved")
	
	

func load_list():
	$FileDialog.window_title = "Load a list"
	$FileDialog.mode = FileDialog.MODE_OPEN_FILE
	
	$FileDialog.popup()
	
	var savefile = yield(get_node("FileDialog"),"file_selected")
	
	var save_game = File.new()
	save_game.open(savefile, File.READ)
	var data = save_game.get_as_text()
	save_game.close()
	
	data = data.split("\n")
	for line in data:
		if line.begins_with("gridsize"):
			var temp_grid_size = int(line.split(" ")[1])
			$Main/Options/GridSize/LineEdit.text = str(temp_grid_size)
			set_grid(temp_grid_size)
			
		if line.begins_with("usefreespace"):
			var temp_freespace = bool(line.split(" ")[1])
			usefreespace = temp_freespace
			$Main/Options/FreeSpace/CheckBox.pressed = temp_freespace
			
		if line.begins_with("entries"):
			var to_disperse: Array
			var tempentries = line.split("[")[1]
			tempentries = tempentries.trim_suffix("]")
			var loadentries = tempentries.split(", ")
			for entrydata in loadentries:
				entrydata.trim_prefix(" ")
				to_disperse.append(entrydata)
				
			print(to_disperse)
			
			for child in $Main/Entries/EntryNav/EntryGrid.get_children():
				child.queue_free()
				
			for array_entry in to_disperse:
				var new_entry = grid_entry.instance()
				new_entry.set_text(array_entry)
				$Main/Entries/EntryNav/EntryGrid.add_child(new_entry)
				
		if line.begins_with("titlecolor"):
			var new_col = split_color(line.split(" ")[1])
			title_color = new_col
			$Main/Options/Colors/TitleCol/TCol.color = new_col
			
		if line.begins_with("textcolor"):
			var new_col = split_color(line.split(" ")[1])
			text_color = new_col
			$Main/Options/Colors/EntryCol/ECol.color = new_col
			
		if line.begins_with("gridcolor"):
			var new_col = split_color(line.split(" ")[1])
			grid_color = new_col
			$Main/Options/Colors/GridCol/GCol.color = new_col
			
		if line.begins_with("textsize"):
			var temp_size = line.split(" ")[1]
			$Main/Options/TextSize/TSizeEdit.text = temp_size
			_on_TSizeEdit_text_changed(temp_size)
	
		print("List Loaded")


	
func update_colors():
	title_color = $Main/Options/Colors/TitleCol/TCol.color
	text_color = $Main/Options/Colors/EntryCol/ECol.color
	grid_color = $Main/Options/Colors/GridCol/GCol.color
	
	for title_child in titlearray.get_children():
		title_child.change_color(title_color)
		
	for grid_child in maingrid.get_children():
		grid_child.color = grid_color	
		grid_child.text_col(text_color)
		


func _on_TSizeEdit_text_changed(new_text):
	var new_size = int(new_text)
	
	if new_size <= 0:
		new_size = 16
		
	for grid_entry in maingrid.get_children():
		grid_entry.text_size(new_size)
		
		
		
func split_color(string):
	var tempr = string.split(",")[0]
	var tempg = string.split(",")[1]
	var tempb = string.split(",")[2]
	return Color(tempr,tempg,tempb)


func generate_cards():
	pass
