1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use std::{cell::RefCell, rc::Rc};

use serde_json::Map;

use crate::{
    callstack::{CallStack, Thread},
    choice::Choice,
    container::Container,
    json_read, json_write,
    object::RTObject,
    story_error::StoryError,
};

#[derive(Clone)]
pub(crate) struct Flow {
    pub name: String,
    pub callstack: Rc<RefCell<CallStack>>,
    pub output_stream: Vec<Rc<dyn RTObject>>,
    pub current_choices: Vec<Rc<Choice>>,
}

impl Flow {
    pub fn new(name: &str, main_content_container: Rc<Container>) -> Flow {
        Flow {
            name: name.to_string(),
            callstack: Rc::new(RefCell::new(CallStack::new(main_content_container))),
            output_stream: Vec::new(),
            current_choices: Vec::new(),
        }
    }

    pub fn from_json(
        name: &str,
        main_content_container: Rc<Container>,
        j_obj: &Map<String, serde_json::Value>,
    ) -> Result<Flow, StoryError> {
        let mut flow = Self {
            name: name.to_string(),
            callstack: Rc::new(RefCell::new(CallStack::new(main_content_container.clone()))),
            output_stream: json_read::jarray_to_runtime_obj_list(
                j_obj
                    .get("outputStream")
                    .ok_or(StoryError::BadJson("outputStream not found.".to_owned()))?
                    .as_array()
                    .unwrap(),
                false,
            )?,
            current_choices: json_read::jarray_to_runtime_obj_list(
                j_obj
                    .get("currentChoices")
                    .ok_or(StoryError::BadJson("currentChoices not found.".to_owned()))?
                    .as_array()
                    .unwrap(),
                false,
            )?
            .iter()
            .map(|o| o.clone().into_any().downcast::<Choice>().unwrap())
            .collect::<Vec<Rc<Choice>>>(),
        };

        flow.callstack.borrow_mut().load_json(
            &main_content_container,
            j_obj
                .get("callstack")
                .ok_or(StoryError::BadJson("loading callstack".to_owned()))?
                .as_object()
                .unwrap(),
        )?;
        let j_choice_threads = j_obj.get("choiceThreads");

        flow.load_flow_choice_threads(j_choice_threads, main_content_container)?;

        Ok(flow)
    }

    pub(crate) fn write_json(&self) -> Result<serde_json::Value, StoryError> {
        let mut flow: Map<String, serde_json::Value> = Map::new();

        flow.insert(
            "callstack".to_owned(),
            self.callstack.borrow().write_json()?,
        );
        flow.insert(
            "outputStream".to_owned(),
            json_write::write_list_rt_objs(&self.output_stream)?,
        );

        // choiceThreads: optional
        // Has to come BEFORE the choices themselves are written out
        // since the originalThreadIndex of each choice needs to be set
        let mut has_choice_threads = false;
        let mut jct: Map<String, serde_json::Value> = Map::new();
        for c in self.current_choices.iter() {
            c.original_thread_index
                .replace(c.get_thread_at_generation().unwrap().thread_index);

            if self
                .callstack
                .borrow()
                .get_thread_with_index(*c.original_thread_index.borrow())
                .is_none()
            {
                if !has_choice_threads {
                    has_choice_threads = true;
                }

                jct.insert(
                    c.original_thread_index.borrow().to_string(),
                    c.get_thread_at_generation().unwrap().write_json()?,
                );
            }
        }

        if has_choice_threads {
            flow.insert("choiceThreads".to_owned(), serde_json::Value::Object(jct));
        }

        let mut c_array: Vec<serde_json::Value> = Vec::new();
        for c in self.current_choices.iter() {
            c_array.push(json_write::write_choice(c));
        }

        flow.insert(
            "currentChoices".to_owned(),
            serde_json::Value::Array(c_array),
        );

        Ok(serde_json::Value::Object(flow))
    }

    pub fn load_flow_choice_threads(
        &mut self,
        j_choice_threads: Option<&serde_json::Value>,
        main_content_container: Rc<Container>,
    ) -> Result<(), StoryError> {
        for choice in self.current_choices.iter_mut() {
            self.callstack
                .borrow()
                .get_thread_with_index(*choice.original_thread_index.borrow())
                .map(|o| choice.set_thread_at_generation(o.clone()))
                .or_else(|| {
                    let j_saved_choice_thread = j_choice_threads
                        .and_then(|c| c.get(choice.original_thread_index.borrow().to_string()))
                        .ok_or("loading choice threads")
                        .unwrap();
                    choice.set_thread_at_generation(
                        Thread::from_json(
                            &main_content_container,
                            j_saved_choice_thread.as_object().unwrap(),
                        )
                        .unwrap(),
                    );
                    Some(())
                });
        }

        Ok(())
    }
}