2022-06-04 13:33:00 +02:00
extends Object
2022-05-14 20:51:48 +02:00
class_name TopicData
2022-06-04 13:33:00 +02:00
signal topic_added ( topic )
signal topic_inserted ( topic , position )
2022-05-14 20:51:48 +02:00
2022-06-05 14:22:08 +02:00
const FILE_NAME = " topic_list.dat "
2022-05-14 20:51:48 +02:00
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 ) :
2022-05-14 20:51:48 +02:00
var topic = Topic . new ( )
loaded_topics . append ( topic )
2022-05-21 14:56:02 +02:00
dirty_flag = true
2022-05-14 20:51:48 +02:00
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 ( )
2022-05-14 20:51:48 +02:00
func load_data ( ) :
2022-06-04 13:33:00 +02:00
var file = File . new ( )
2022-06-05 14:22:08 +02:00
file . open ( " user:// " + FILE_NAME , File . READ )
2022-06-04 13:33:00 +02:00
var json_string = file . get_as_text ( )
if validate_json ( json_string ) :
2022-06-05 14:22:08 +02:00
printerr ( " \" " + FILE_NAME + " \" was found, but is corrupted. " )
2022-06-04 13:33:00 +02:00
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 " ] )
)
2022-05-14 20:51:48 +02:00
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 ( )
2022-06-05 14:22:08 +02:00
file . open ( " user:// " + FILE_NAME , File . WRITE )
2022-06-04 13:33:00 +02:00
file . store_string ( json_string )
file . close ( )
2022-05-14 20:51:48 +02:00
# dirty_flag needs to be set to false after successful save!
dirty_flag = false