diary/system/data/topic_data/topic_data_singleton.gd

69 lines
1.6 KiB
GDScript3
Raw Normal View History

2022-06-04 13:33:00 +02:00
extends Object
class_name TopicData
2022-06-04 13:33:00 +02:00
signal topic_added(topic)
signal topic_inserted(topic, position)
var dirty_flag = false
var loaded_topics = []
2022-06-04 13:33:00 +02:00
func add_topic(content, type): # On start-up.
var topic = Topic.new()
topic.content = content
topic.type = type
loaded_topics.append(topic)
emit_signal("topic_added", topic)
func insert_topic(position: int):
var topic = Topic.new()
loaded_topics.append(topic)
2022-05-21 14:56:02 +02:00
dirty_flag = true
2022-06-04 13:33:00 +02:00
emit_signal("topic_inserted", topic, position)
2022-05-21 14:56:02 +02:00
func sort_topics():
loaded_topics.sort_custom(self, "_compare_topic_index")
func _compare_topic_index(a, b):
return a.associated_node.parent.get_index() < b.associated_node.parent.get_index()
func load_data():
2022-06-04 13:33:00 +02:00
var file = File.new()
file.open("user://topic_list.dat", File.READ)
var json_string = file.get_as_text()
if validate_json(json_string):
printerr("\"topic_list.dat\" was found, but is corrupted.")
return
var topic_data_list = parse_json(json_string)
for topic_data in topic_data_list:
add_topic(
topic_data["content"],
int(topic_data["type"])
)
func save_data():
if dirty_flag:
2022-05-21 14:56:02 +02:00
sort_topics() # Important before saving, to remain the order.
2022-06-04 13:33:00 +02:00
var topic_data_list = []
for topic in loaded_topics:
var topic_data = {
"content" : topic.content,
"type" : topic.type
}
topic_data_list.append(topic_data)
var json_string = to_json(topic_data_list)
var file = File.new()
file.open("user://topic_list.dat", File.WRITE)
file.store_string(json_string)
file.close()
# dirty_flag needs to be set to false after successful save!
dirty_flag = false