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
185
186
187
use std::fmt::Display;

use super::{topic::DbTopic, *};

use crate::{
    api::types::problemset_question_list::Question,
    errors::{DBResult, DbErr},
};

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[native_model(id = 1, version = 1)]
#[native_db]
pub struct DbQuestion {
    #[primary_key]
    pub id: u32,
    pub title: String,
    pub title_slug: String,
    pub difficulty: String,
    pub paid_only: bool,
    pub status: Option<String>,
    pub topics: Vec<DbTopic>,
}

impl Display for DbQuestion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut w = String::new();
        w.push_str(if self.paid_only { "🔐" } else { "  " });
        w.push_str(if self.status.is_none() {
            "  "
        } else if self.status == Some("ac".into()) {
            "👑"
        } else {
            "🏃"
        });
        w.push_str(self.title.as_str());
        write!(f, "{: >4}{w}", self.id)
    }
}

impl DbQuestion {
    pub fn is_hard(&self) -> bool {
        self.difficulty == "Hard"
    }

    pub fn is_medium(&self) -> bool {
        self.difficulty == "Medium"
    }

    pub fn is_easy(&self) -> bool {
        self.difficulty == "Easy"
    }
}

impl TryFrom<Question> for DbQuestion {
    type Error = DbErr;

    fn try_from(
        value: crate::api::types::problemset_question_list::Question,
    ) -> Result<Self, Self::Error> {
        let mut db_quest = DbQuestion::new(
            value.frontend_question_id.parse()?,
            value.title.as_str(),
            value.title_slug.as_str(),
            value.difficulty,
            value.paid_only,
            value.status,
        );
        if let Some(tts) = value.topic_tags {
            if !tts.is_empty() {
                for topic in tts {
                    db_quest.add_topic(topic.slug.as_str());
                }
            } else {
                db_quest.add_topic("unknown");
            }
        }
        Ok(db_quest)
    }
}

impl DbQuestion {
    pub fn new(
        id: u32,
        title: &str,
        title_slug: &str,
        difficulty: String,
        paid_only: bool,
        status: Option<String>,
    ) -> Self {
        Self {
            id,
            title: title.into(),
            title_slug: title_slug.into(),
            topics: Default::default(),
            difficulty,
            paid_only,
            status,
        }
    }

    fn add_topic(&mut self, slug: &str) {
        self.topics.push(DbTopic::new(slug))
    }

    pub fn mark_accepted<'a>(&mut self, db: &'a Database<'a>) -> DBResult<Option<Vec<Self>>> {
        if self.status.is_none() || self.status == Some("notac".into()) {
            self.status = Some("ac".into());
            return Ok(Some(self.update_in_db(db)?));
        }
        Ok(None)
    }

    pub fn mark_attempted<'a>(&mut self, db: &'a Database<'a>) -> DBResult<Option<Vec<Self>>> {
        if self.status.is_none() {
            self.status = Some("notac".into());
            return Ok(Some(self.update_in_db(db)?));
        }
        Ok(None)
    }

    fn update_in_db<'a>(&self, db: &'a Database<'a>) -> DBResult<Vec<Self>> {
        let rw = db.rw_transaction()?;
        let old = Self::get_question_by_id(db, self.id)?;
        rw.update(old, self.clone())?;
        rw.commit()?;
        Ok(vec![self.clone()])
    }

    pub fn get_total_questions<'a>(db: &'a Database<'a>) -> DBResult<usize> {
        let r = db.r_transaction()?;
        let x = r.scan().primary::<Self>()?;
        Ok(x.all().count())
    }

    pub fn get_question_by_id<'a>(db: &'a Database<'a>, id: u32) -> DBResult<Self> {
        let r = db.r_transaction()?;
        let x = r
            .get()
            .primary::<DbQuestion>(id)?
            .ok_or(DbErr::QuestionsNotFoundInDb(id.to_string()))?;
        // x.topics = x.fetch_all_topics(db)?;
        Ok(x)
    }

    fn save_all_topics<'a>(&mut self, db: &'a Database<'a>) -> DBResult<()> {
        for topic in self.topics.iter() {
            topic.save_to_db(db)?;
        }
        Ok(())
    }

    // pub fn fetch_all_topics<'a>(&self, db: &'a Database<'a>) -> DBResult<Vec<DbTopic>> {
    //     let q_topic_map = QuestionTopicMap::get_all_topic_slug_by_question(self, db)?;
    //     let mut topics = vec![];

    //     for topic_slug in q_topic_map {
    //         topics.push(DbTopic::get_topic_by_slug(topic_slug.as_str(), db)?);
    //     }
    //     Ok(topics)
    // }

    pub(crate) fn get_topics(&self) -> &Vec<DbTopic> {
        &self.topics
    }

    pub fn save_to_db<'a>(&mut self, db: &'a Database<'a>) -> DBResult<bool> {
        // save Topic -> Question Mapping
        TopicQuestionMap::save_mapping(self, db)?;

        // save Question -> Topic Mapping
        QuestionTopicMap::save_mapping(self, db)?;

        // save DbTopics for the question
        self.save_all_topics(db)?;

        // save question
        save(self.clone(), db)?;
        return Ok(true);
    }
}

fn save<'a, T: Input>(item: T, db: &'a Database<'a>) -> DBResult<()> {
    let rw = db.rw_transaction()?;
    rw.insert(item)?;
    rw.commit()?;
    Ok(())
}