Загрузка данных


extends Control
var Itemsbase 
var Collbase
var path = "user://"
var path_to_item_json = "user://JSON/Itemsbase.json"
var path_to_coll_json = "user://JSON/Collbase.json"
var rendered_items = []
var rendered_coll = []
var current_item
var chosencollection
var thing_to_delete
'''
exampleitem = [
	"name": String
	"description": String
	"date": String
	"pic": String
	"coll_id": int
	"id": int
	"collected": bool
]
exampleColl = [
	"name": ""
	"id": int
]
'''




func save_pic(path):
	pass
	
func deletething(thing):
	if thing == chosencollection:
		Itemsbase = Itemsbase.filter(func(item): return item["coll_id"] != thing["id"])	
		Collbase.erase(thing)
		chosencollection = {} 
		current_item = {}     	
	elif thing == current_item:
		Itemsbase.erase(thing)
		current_item = {} 
		
		
func save_all_data(pathtofile, data):
	var file = FileAccess.open(pathtofile, FileAccess.WRITE_READ)
	file.store_string(JSON.stringify(data, "\t"))
	print("saved JSON!")
	file.close()
	if chosencollection is Dictionary:
		renderItems(chosencollection["id"])
	render_collections()
	
# Called when the node enters the scene tree for the first time.
func renderItems(index):
	$COLLWINDOW/VBoxContainer/HBoxContainer/collectables.clear()
	if not rendered_items.size() == 0:
		rendered_items.clear()
	for item in Itemsbase:
		if item["coll_id"] == index:
			rendered_items.append(item)
			$COLLWINDOW/VBoxContainer/HBoxContainer/collectables.add_item(item["name"])
	rendered_items.sort_custom(func(a, b):
			return a["id"] < b["id"]
	)
	if rendered_items.is_empty():
		$COLLWINDOW/VBoxContainer/HBoxContainer/collectables.clear()
		$COLLWINDOW/VBoxContainer/HBoxContainer/collectables.add_item("Nothing found"); $COLLWINDOW/VBoxContainer/HBoxContainer/collectables.set_item_disabled(0, true)
	
	
func _on_SaveCollectionName(name):
	chosencollection["name"] = name
	save_all_data(path_to_coll_json, Collbase)
	
	
	
func _on_savePic(picpath):
	current_item["pic"] = str(picpath)
	var pathy = path + "PICS"
	save_pic(pathy)
	
	
func _on_saveDesc(description):
	current_item["description"] = str(description)
	save_all_data(path_to_item_json, Itemsbase)

func _on_saveDate(date):
	current_item["date"] = str(date)

	save_all_data(path_to_item_json, Itemsbase)

func _on_saveName(gotname):
	print("_on_saveName")
	current_item["name"] = str(gotname)
	
	save_all_data(path_to_item_json, Itemsbase)
	
	
func _on_check_button_toggled(toggled_on: bool) -> void:
	current_item["collected"] = toggled_on

	save_all_data(path_to_item_json, Itemsbase)



func _ready() -> void:
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/NameContainer.saveName.connect(_on_saveName)
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/DateContainer.saveDate.connect(_on_saveDate)
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/DescriptionContainer.saveDescription.connect(_on_saveDesc)
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/PictureContainer.savePicture.connect(_on_savePic)
	$COLLWINDOW/VBoxContainer/HBoxContainer/Control.saveCollectionName.connect(_on_SaveCollectionName)
	$COLLWINDOW.visible = false
	$Welcomewin.visible = true
	if !DirAccess.dir_exists_absolute("user://JSON"):
		DirAccess.make_dir_absolute("user://JSON")
	if !DirAccess.dir_exists_absolute("user://PICS"):
		DirAccess.make_dir_absolute("user://PICS")
	if !FileAccess.file_exists("user://JSON/Itemsbase.json"): var filetest = FileAccess.open("user://JSON/Itemsbase.json", FileAccess.WRITE); filetest.close()
	if !FileAccess.file_exists("user://JSON/Collbase.json"): var filetest = FileAccess.open("user://JSON/Collbase.json", FileAccess.WRITE); filetest.close()
	var now = Time.get_unix_time_from_system()
	var file = FileAccess.open("user://JSON/Itemsbase.json", FileAccess.READ)
	var string = file.get_as_text()
	Itemsbase = JSON.parse_string(string)
	if Itemsbase is Array:
		for i in range(Itemsbase.size()):
			print(Itemsbase[i])
	else:
		push_warning("Itemlist is not an array!")
		Itemsbase = []
	var filecoll = FileAccess.open("user://JSON/Collbase.json", FileAccess.READ)
	var stringcoll = filecoll.get_as_text()
	Collbase = JSON.parse_string(stringcoll)
	if Collbase is Array:
		for i in range(Collbase.size()):
			print(Collbase[i])
	else:
		push_warning("Collbase is not an array!")
		Collbase = []
	if Collbase is Array and Itemsbase is Array:
		Collbase.sort_custom(func(a, b):
			return a["id"] < b["id"]
		)
		Itemsbase.sort_custom(func(a, b):
			return a["id"] < b["id"]
		)
	var text = "Затрачаено: " + str(Time.get_unix_time_from_system() - now).substr(0, 5) + "мс"
	
	$COLLWINDOW/HBoxContainer/Buttons/HBoxContainer/timer.text = text


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass
	
	
func mainwindow():
	pass
	
func render_collections():
	$COLLWINDOW/VBoxContainer/HBoxContainer/Control/collections.clear()
	print("Collbase")
	print(Collbase)
	print("Collbase is Array" + str(Collbase is Array))
	if not Collbase.is_empty():
		$COLLWINDOW/VBoxContainer/HBoxContainer/Control/collections.clear()
		for coll in Collbase:
			$COLLWINDOW/VBoxContainer/HBoxContainer/Control/collections.add_item(coll["name"])
	elif Collbase.is_empty(): 
		print("NOT_FOUND#1")
		$COLLWINDOW/VBoxContainer/HBoxContainer/Control/collections.add_item("Nothing found")
		$COLLWINDOW/VBoxContainer/HBoxContainer/Control/collections.set_item_disabled(0, true)
	
func _on_button_pressed() -> void:
	$Welcomewin.visible = false
	$COLLWINDOW.visible = true
	render_collections()
	


func _on_collections_item_selected(index: int) -> void:
	renderItems(index + 1)
	chosencollection = Collbase[index]
	$COLLWINDOW/HBoxContainer/Buttons/PanelContainer/HBoxContainer/deletechoice.add_item(chosencollection)
	$COLLWINDOW/HBoxContainer/Buttons/add.disabled = false


func _on_collectables_item_selected(index: int) -> void:
	$COLLWINDOW/HBoxContainer/Buttons/PanelContainer/HBoxContainer/deletechoice.add_item(current_item)
	var namemsd = $COLLWINDOW/VBoxContainer/HBoxContainer/collectables.get_item_text(index)
	
	var item = rendered_items[index]
	for i in range(Itemsbase.size()):
		if Itemsbase[i]["id"] == item["id"]:
			current_item = Itemsbase[i]
			
	if item["pic"] == "":
		$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/PictureContainer/HBoxContainer/CollectablePIC.texture = load("res://Nophoto.png")
	else: 
		var picpath = []
		picpath.append(path)
		picpath.append("PICS")
		picpath.append(item["pic"])
		var fullpath = "/".join(picpath)
		var image = Image.new()
		image.load(fullpath)
		var texture = ImageTexture.create_from_image(image)
		$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/PictureContainer/HBoxContainer/CollectablePIC.texture = texture
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/NameContainer/Name.text = item["name"]
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/DateContainer/Date.text = item["date"]
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/DescriptionContainer/Description.text = item["description"]
	$COLLWINDOW/VBoxContainer/HBoxContainer/PanelContainer/HBoxContainer/VBoxContainer/HBoxContainer2/CheckButton.button_pressed = item["collected"]
				
				


func _on_add_pressed() -> void:
	
	if chosencollection is Dictionary and chosencollection.has("id"):
		var colid = chosencollection["id"]
		
		
		var max_id = 0
		for item in Itemsbase:
			if item["id"] > max_id:
				max_id = item["id"]
		
		var next_id = max_id + 1 if not Itemsbase.is_empty() else 1

		
		var max_number = 0
		for item in Itemsbase:
			var item_name: String = item["name"]
			if item_name.begins_with("element"):
				var number = item_name.substr(7).to_int()
				if number > max_number:
					max_number = number
		
		var nameing = "element" + str(max_number + 1)
		
		
		var new_item = {
			"name": nameing,
			"description": "",
			"date": "",
			"pic": "",
			"coll_id": colid,
			"id": next_id,
			"collected": false
		}
		
		Itemsbase.append(new_item)
		save_all_data(path_to_item_json, Itemsbase)
		renderItems(colid)
	else:
		print("Failed to create element, try again later")


func _on_addcollection_pressed() -> void:
	
	var max_id = 0
	for coll in Collbase:
		if coll["id"] > max_id:
			max_id = coll["id"]
	
	var next_id = max_id + 1 if not Collbase.is_empty() else 1
	
	
	var max_number = 0
	for coll in Collbase:
		var coll_name: String = coll["name"]
		if coll_name.begins_with("collection"):
			var number = coll_name.substr(10).to_int()
			if number > max_number:
				max_number = number
	
	var nameing = "collection" + str(max_number + 1)

	var new_collection = {
		"name": nameing,
		"id": next_id
	}
	
	Collbase.append(new_collection)
	save_all_data(path_to_coll_json, Collbase)
	render_collections()


func _on_deletechoice_item_selected(index: int) -> void:
	$COLLWINDOW/HBoxContainer/Buttons/PanelContainer/HBoxContainer/delete.disabled = false
	thing_to_delete = $COLLWINDOW/HBoxContainer/Buttons/PanelContainer/HBoxContainer/deletechoice.get_item_index(index)


func _on_delete_pressed() -> void:
	deletething(thing_to_delete)