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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use std::{cell::RefCell, collections::HashMap, fmt::Display, rc::Rc};

use indexmap::IndexMap;

use crate::{
    app_ui::async_task_channel::Response,
    deserializers::editor_data,
    deserializers::{
        question_content::QuestionContent,
        run_submit::{self, ParsedResponse, Success},
    },
    entities::{QuestionModel, TopicTagModel},
};

#[derive(Debug)]
pub(super) enum TaskType {
    Run,
    Edit,
    Read,
    Submit,
}

pub(super) fn process_get_all_question_map_task_content(
    content: HashMap<TopicTagModel, Vec<QuestionModel>>,
    topic_tag_question_map: &mut HashMap<Rc<TopicTagModel>, Vec<super::Question>>,
    question_id_question_map: &mut IndexMap<String, super::Question>,
) {
    // creating rc cloned question as one question can appear in multiple topics
    // create (frontend_question_id, QuestionModel) mapping
    let question_set = content
        .iter()
        .flat_map(|x| {
            x.1.iter().map(|x| {
                (
                    x.frontend_question_id.clone(),
                    Rc::new(RefCell::new(x.clone())),
                )
            })
        })
        .collect::<IndexMap<_, _>>();

    // (topic_tag, question_mapping)
    let map_iter = content.into_iter().map(|v| {
        (
            Rc::new(v.0),
            (v.1.into_iter()
                .map(|x| question_set[&x.frontend_question_id].clone()))
            .collect::<Vec<_>>(),
        )
    });

    let all_questions = question_set.values().cloned().collect();

    topic_tag_question_map.extend(map_iter);
    topic_tag_question_map.extend(vec![(
        Rc::new(TopicTagModel {
            name: "All".to_owned(),
            id: "all".to_owned(),
            slug: "all".to_owned(),
        }),
        all_questions,
    )]);

    for ql in topic_tag_question_map.values_mut() {
        ql.sort_unstable()
    }

    *question_id_question_map = question_set;
    question_id_question_map.sort_by(|_, y, _, k| y.cmp(k));
}

pub(super) fn process_question_detail_response(
    response: Response<QuestionContent>,
    task_map: &mut HashMap<String, (super::Question, super::TaskType)>,
    cache: &mut lru::LruCache<String, super::CachedQuestion>,
) {
    let key = task_map
        .remove(&response.request_id)
        .expect("sent task is not found in the task list.")
        .0
        .borrow()
        .frontend_question_id
        .clone();
    let cached_q = cache.get_or_insert_mut(key, super::CachedQuestion::default);
    cached_q.qd = Some(response.content);
}

pub(super) fn process_question_editor_data(
    response: Response<editor_data::Question>,
    task_map: &mut HashMap<String, (super::Question, super::TaskType)>,
    cache: &mut lru::LruCache<String, super::CachedQuestion>,
) {
    let key = task_map
        .remove(&response.request_id)
        .expect("sent task is not found in the task list.")
        .0
        .borrow()
        .frontend_question_id
        .clone();
    let cached_q = cache.get_or_insert_mut(key, super::CachedQuestion::default);
    cached_q.editor_data = Some(response.content);
}

impl Display for run_submit::ParsedResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let string = match &self {
            ParsedResponse::Pending => "Pending".to_string(),
            ParsedResponse::CompileError(_) => "Compile Error".to_string(),
            ParsedResponse::RuntimeError(_) => "Runtime Error".to_string(),
            ParsedResponse::MemoryLimitExceeded(_) => "Memory Limit Exceeded".to_string(),
            ParsedResponse::OutputLimitExceed(_) => "Output Limit Exceeded".to_string(),
            ParsedResponse::TimeLimitExceeded(_) => "Time Limit Exceeded".to_string(),
            ParsedResponse::InternalError(_) => "Internal Error".to_string(),
            ParsedResponse::TimeOut(_) => "Timout".to_string(),
            ParsedResponse::Unknown(_) => "Unknown".to_string(),
            ParsedResponse::Success(Success::Run {
                status_runtime,
                code_answer,
                expected_code_answer,
                correct_answer,
                total_correct,
                total_testcases,
                status_memory,
                ..
            }) => {
                let is_accepted_symbol = if *correct_answer { "✅" } else { "❌" };
                let mut ans_compare = String::new();
                for (output, expected_output) in code_answer.iter().zip(expected_code_answer) {
                    let emoji = if output == expected_output {
                        "✅"
                    } else {
                        "❌"
                    };
                    let compare = format!(
                        "{emoji}\nOuput: {}\nExpected: {}\n\n",
                        output, expected_output
                    );
                    ans_compare.push_str(compare.as_str())
                }
                let result_string = vec![
                    format!("Accepted: {}", is_accepted_symbol),
                    if let Some(correct) = total_correct {
                        let mut x = format!("Correct: {correct}");
                        if let Some(total) = total_testcases {
                            x = format!("{x}/{}", total);
                        }
                        x
                    } else {
                        String::new()
                    },
                    format!("Memory Used: {status_memory}"),
                    format!("Status Runtime: {status_runtime}"),
                    ans_compare,
                ];
                result_string.join("\n")
            }
            ParsedResponse::Success(Success::Submit {
                status_runtime,
                total_correct,
                total_testcases,
                status_memory,
                ..
            }) => {
                let is_accepted_symbol = "✅";
                let result_string = vec![
                    format!("Accepted: {}", is_accepted_symbol),
                    if let Some(correct) = total_correct {
                        let mut x = format!("Correct: {correct}");
                        if let Some(total) = total_testcases {
                            x = format!("{x}/{}", total);
                        }
                        x
                    } else {
                        String::new()
                    },
                    format!("Memory Used: {status_memory}"),
                    format!("Status Runtime: {status_runtime}"),
                ];
                result_string.join("\n")
            }
        };
        f.write_fmt(format_args!("{string}"))
    }
}