diary/system/data/message_data/message_data_singleton.gd

87 lines
2.4 KiB
GDScript3
Raw Normal View History

2022-06-04 13:33:00 +02:00
extends Object
class_name MessageData
signal message_added(message)
signal message_group_added(message_group)
var dirty_flag = false
var loaded_message_groups = []
func add_message(content, time_stamp, user):
var message_group: MessageGroup
if loaded_message_groups.empty():
message_group = _add_message_group(time_stamp, user)
else:
var latest_message_group = loaded_message_groups[-1]
if latest_message_group.associated_user != user:
message_group = _add_message_group(time_stamp, user)
else:
var latest_message = latest_message_group.messages[-1]
if time_stamp - latest_message.time_stamp >= 120:
message_group = _add_message_group(time_stamp, user)
else:
message_group = loaded_message_groups[-1]
var message = Message.new()
message.content = content
message.time_stamp = time_stamp
message_group.add(message)
emit_signal("message_added", message)
2022-06-04 13:33:00 +02:00
dirty_flag = true
func load_data():
2022-06-04 13:33:00 +02:00
var file = File.new()
file.open("user://message_history.dat", File.READ)
var json_string = file.get_as_text()
if validate_json(json_string):
printerr("\"message_history.dat\" was found, but is corrupted.")
return
var message_data_list = parse_json(json_string)
for message_data in message_data_list:
var user = Users.get_primary() if message_data["user"] else Users.get_helper()
add_message(
message_data["content"],
message_data["time_stamp"],
user
)
func save_data():
if dirty_flag:
2022-06-04 13:33:00 +02:00
var message_data_list = []
for message_group in loaded_message_groups:
var user = message_group.associated_user.is_primary()
for message in message_group.messages:
var message_data = {
"user" : user,
"time_stamp" : message.time_stamp,
"content" : message.content
}
message_data_list.append(message_data)
var json_string = to_json(message_data_list)
var file = File.new()
file.open("user://message_history.dat", File.WRITE)
file.store_string(json_string)
file.close()
# dirty_flag needs to be set to false after successful save!
dirty_flag = false
func _add_message_group(time_stamp, user) -> MessageGroup:
var message_group = MessageGroup.new()
message_group.associated_user = user
message_group.time_stamp = time_stamp
loaded_message_groups.append(message_group)
emit_signal("message_group_added", message_group)
# var container = message_group.create_container()
# UI.message_feed_container.add_child(container)
return message_group