diary/system/data/message_data/message_data_singleton.gd
2022-06-05 14:22:08 +02:00

110 lines
3.0 KiB
GDScript

extends Object
class_name MessageData
signal message_added(message)
signal message_group_added(message_group)
const FILE_NAME = "message_history.dat"
const MAX_MESSAGES = 200
var dirty_flag = false
var loaded_message_groups = []
var message_count = 0
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)
message_count += 1
if message_count > MAX_MESSAGES:
get_first_message().delete()
emit_signal("message_added", message)
dirty_flag = true
func get_first_message() -> Message:
if loaded_message_groups.empty():
return null
else:
return loaded_message_groups[0].messages[0]
func get_last_message_of_user(user: User) -> Message:
if not loaded_message_groups.empty():
for i in range(loaded_message_groups.size() -1, -1, -1):
var message_group = loaded_message_groups[i]
if message_group.associated_user == user:
return loaded_message_groups[i].messages[-1]
return null
func load_data():
var file = File.new()
file.open("user://" + FILE_NAME, File.READ)
var json_string = file.get_as_text()
if validate_json(json_string):
printerr("\"" + FILE_NAME + "\" 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:
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://" + FILE_NAME, 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