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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/* This file is part of DarkFi (https://dark.fi)
 *
 * Copyright (C) 2020-2024 Dyne.org foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use std::{
    collections::HashMap,
    fmt,
    path::{Path, PathBuf},
    str::FromStr,
};

use darkfi_serial::{async_trait, SerialDecodable, SerialEncodable};
use log::debug;
use tinyjson::JsonValue;

use darkfi::{
    util::{
        file::{load_json_file, save_json_file},
        time::Timestamp,
    },
    Error,
};

use crate::{
    error::{TaudError, TaudResult},
    month_tasks::MonthTasks,
    util::gen_id,
};

pub enum State {
    Open,
    Start,
    Pause,
    Stop,
}

impl State {
    pub const fn is_start(&self) -> bool {
        matches!(*self, Self::Start)
    }
    pub const fn is_pause(&self) -> bool {
        matches!(*self, Self::Pause)
    }
    pub const fn is_stop(&self) -> bool {
        matches!(*self, Self::Stop)
    }
}

impl fmt::Display for State {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            State::Open => write!(f, "open"),
            State::Start => write!(f, "start"),
            State::Stop => write!(f, "stop"),
            State::Pause => write!(f, "pause"),
        }
    }
}

impl FromStr for State {
    type Err = Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let result = match s.to_lowercase().as_str() {
            "open" => State::Open,
            "stop" => State::Stop,
            "start" => State::Start,
            "pause" => State::Pause,
            _ => return Err(Error::ParseFailed("unable to parse state")),
        };
        Ok(result)
    }
}

#[derive(Clone, Debug, SerialEncodable, SerialDecodable, PartialEq, Eq)]
pub struct TaskEvent {
    pub action: String,
    pub author: String,
    pub content: String,
    pub timestamp: Timestamp,
}

impl std::fmt::Display for TaskEvent {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "action: {}, timestamp: {}", self.action, self.timestamp)
    }
}

impl Default for TaskEvent {
    fn default() -> Self {
        Self {
            action: State::Open.to_string(),
            author: "".to_string(),
            content: "".to_string(),
            timestamp: Timestamp::current_time(),
        }
    }
}

impl TaskEvent {
    pub fn new(action: String, author: String, content: String) -> Self {
        Self { action, author, content, timestamp: Timestamp::current_time() }
    }
}

impl From<TaskEvent> for JsonValue {
    fn from(task_event: TaskEvent) -> JsonValue {
        JsonValue::Object(HashMap::from([
            ("action".to_string(), JsonValue::String(task_event.action.clone())),
            ("author".to_string(), JsonValue::String(task_event.author.clone())),
            ("content".to_string(), JsonValue::String(task_event.content.clone())),
            ("timestamp".to_string(), JsonValue::String(task_event.timestamp.inner().to_string())),
        ]))
    }
}

impl From<&JsonValue> for TaskEvent {
    fn from(value: &JsonValue) -> TaskEvent {
        let map = value.get::<HashMap<String, JsonValue>>().unwrap();
        TaskEvent {
            action: map["action"].get::<String>().unwrap().clone(),
            author: map["author"].get::<String>().unwrap().clone(),
            content: map["content"].get::<String>().unwrap().clone(),
            timestamp: Timestamp::from_u64(
                map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap(),
            ),
        }
    }
}

#[derive(Clone, Debug, SerialDecodable, SerialEncodable, PartialEq, Eq)]
pub struct Comment {
    content: String,
    author: String,
    timestamp: Timestamp,
}

impl std::fmt::Display for Comment {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{} author: {}, content: {} ", self.timestamp, self.author, self.content)
    }
}

impl From<Comment> for JsonValue {
    fn from(comment: Comment) -> JsonValue {
        JsonValue::Object(HashMap::from([
            ("content".to_string(), JsonValue::String(comment.content.clone())),
            ("author".to_string(), JsonValue::String(comment.author.clone())),
            ("timestamp".to_string(), JsonValue::String(comment.timestamp.inner().to_string())),
        ]))
    }
}

impl From<JsonValue> for Comment {
    fn from(value: JsonValue) -> Comment {
        let map = value.get::<HashMap<String, JsonValue>>().unwrap();
        Comment {
            content: map["content"].get::<String>().unwrap().clone(),
            author: map["author"].get::<String>().unwrap().clone(),
            timestamp: Timestamp::from_u64(
                map["timestamp"].get::<String>().unwrap().parse::<u64>().unwrap(),
            ),
        }
    }
}

impl Comment {
    pub fn new(content: &str, author: &str) -> Self {
        Self {
            content: content.into(),
            author: author.into(),
            timestamp: Timestamp::current_time(),
        }
    }
}

#[derive(Clone, Debug, SerialEncodable, SerialDecodable, PartialEq)]
pub struct TaskInfo {
    pub ref_id: String,
    pub workspace: String,
    pub title: String,
    pub tags: Vec<String>,
    pub desc: String,
    pub owner: String,
    pub assign: Vec<String>,
    pub project: Vec<String>,
    pub due: Option<Timestamp>,
    pub rank: Option<f32>,
    pub created_at: Timestamp,
    pub state: String,
    pub events: Vec<TaskEvent>,
    pub comments: Vec<Comment>,
}

impl From<&TaskInfo> for JsonValue {
    fn from(task: &TaskInfo) -> JsonValue {
        let ref_id = JsonValue::String(task.ref_id.clone());
        let workspace = JsonValue::String(task.workspace.clone());
        let title = JsonValue::String(task.title.clone());
        let tags: Vec<JsonValue> = task.tags.iter().map(|x| JsonValue::String(x.clone())).collect();
        let desc = JsonValue::String(task.desc.clone());
        let owner = JsonValue::String(task.owner.clone());

        let assign: Vec<JsonValue> =
            task.assign.iter().map(|x| JsonValue::String(x.clone())).collect();

        let project: Vec<JsonValue> =
            task.project.iter().map(|x| JsonValue::String(x.clone())).collect();

        let due = if let Some(ts) = task.due {
            JsonValue::String(ts.inner().to_string())
        } else {
            JsonValue::Null
        };

        let rank = if let Some(rank) = task.rank {
            JsonValue::Number(rank.into())
        } else {
            JsonValue::Null
        };

        let created_at = JsonValue::String(task.created_at.inner().to_string());
        let state = JsonValue::String(task.state.clone());
        let events: Vec<JsonValue> = task.events.iter().map(|x| x.clone().into()).collect();
        let comments: Vec<JsonValue> = task.comments.iter().map(|x| x.clone().into()).collect();

        JsonValue::Object(HashMap::from([
            ("ref_id".to_string(), ref_id),
            ("workspace".to_string(), workspace),
            ("title".to_string(), title),
            ("tags".to_string(), JsonValue::Array(tags)),
            ("desc".to_string(), desc),
            ("owner".to_string(), owner),
            ("assign".to_string(), JsonValue::Array(assign)),
            ("project".to_string(), JsonValue::Array(project)),
            ("due".to_string(), due),
            ("rank".to_string(), rank),
            ("created_at".to_string(), created_at),
            ("state".to_string(), state),
            ("events".to_string(), JsonValue::Array(events)),
            ("comments".to_string(), JsonValue::Array(comments)),
        ]))
    }
}

impl From<JsonValue> for TaskInfo {
    fn from(value: JsonValue) -> TaskInfo {
        let tags = value["tags"].get::<Vec<JsonValue>>().unwrap();
        let assign = value["assign"].get::<Vec<JsonValue>>().unwrap();
        let project = value["project"].get::<Vec<JsonValue>>().unwrap();
        let events = value["events"].get::<Vec<JsonValue>>().unwrap();
        let comments = value["comments"].get::<Vec<JsonValue>>().unwrap();

        let due = {
            if value["due"].is_null() {
                None
            } else {
                let u64_str = value["due"].get::<String>().unwrap();
                Some(Timestamp::from_u64(u64_str.parse::<u64>().unwrap()))
            }
        };

        let rank = {
            if value["rank"].is_null() {
                None
            } else {
                Some(*value["rank"].get::<f64>().unwrap() as f32)
            }
        };

        let created_at = {
            let u64_str = value["created_at"].get::<String>().unwrap();
            Timestamp::from_u64(u64_str.parse::<u64>().unwrap())
        };

        let events: Vec<TaskEvent> = events.iter().map(|x| x.into()).collect();
        let comments: Vec<Comment> = comments.iter().map(|x| (*x).clone().into()).collect();

        TaskInfo {
            ref_id: value["ref_id"].get::<String>().unwrap().clone(),
            workspace: value["workspace"].get::<String>().unwrap().clone(),
            title: value["title"].get::<String>().unwrap().clone(),
            tags: tags.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
            desc: value["desc"].get::<String>().unwrap().clone(),
            owner: value["owner"].get::<String>().unwrap().clone(),
            assign: assign.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
            project: project.iter().map(|x| x.get::<String>().unwrap().clone()).collect(),
            due,
            rank,
            created_at,
            state: value["state"].get::<String>().unwrap().clone(),
            events,
            comments,
        }
    }
}

impl TaskInfo {
    pub fn new(
        workspace: String,
        title: &str,
        desc: &str,
        owner: &str,
        due: Option<Timestamp>,
        rank: Option<f32>,
        created_at: Timestamp,
    ) -> TaudResult<Self> {
        // generate ref_id
        let ref_id = gen_id(30);

        if let Some(d) = &due {
            if *d < Timestamp::current_time() {
                return Err(TaudError::InvalidDueTime)
            }
        }

        Ok(Self {
            ref_id,
            workspace,
            title: title.into(),
            desc: desc.into(),
            owner: owner.into(),
            tags: vec![],
            assign: vec![],
            project: vec![],
            due,
            rank,
            created_at,
            state: "open".into(),
            comments: vec![],
            events: vec![],
        })
    }

    pub fn load(ref_id: &str, dataset_path: &Path) -> TaudResult<Self> {
        debug!(target: "tau", "TaskInfo::load()");
        let task = load_json_file(&Self::get_path(ref_id, dataset_path))?;
        Ok(task.into())
    }

    pub fn save(&self, dataset_path: &Path) -> TaudResult<()> {
        debug!(target: "tau", "TaskInfo::save()");
        save_json_file(&Self::get_path(&self.ref_id, dataset_path), &self.into(), true)
            .map_err(TaudError::Darkfi)?;

        if self.get_state() == "stop" {
            self.deactivate(dataset_path)?;
        } else {
            self.activate(dataset_path)?;
        }

        Ok(())
    }

    pub fn activate(&self, path: &Path) -> TaudResult<()> {
        debug!(target: "tau", "TaskInfo::activate()");
        let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
        mt.add(&self.ref_id);
        mt.save(path)
    }

    pub fn deactivate(&self, path: &Path) -> TaudResult<()> {
        debug!(target: "tau", "TaskInfo::deactivate()");
        let mut mt = MonthTasks::load_or_create(Some(&self.created_at), path)?;
        mt.remove(&self.ref_id);
        mt.save(path)
    }

    pub fn get_state(&self) -> String {
        debug!(target: "tau", "TaskInfo::get_state()");
        self.state.clone()
    }

    pub fn get_path(ref_id: &str, dataset_path: &Path) -> PathBuf {
        debug!(target: "tau", "TaskInfo::get_path()");
        dataset_path.join("task").join(ref_id)
    }

    pub fn get_ref_id(&self) -> String {
        debug!(target: "tau", "TaskInfo::get_ref_id()");
        self.ref_id.clone()
    }

    pub fn set_title(&mut self, title: &str) {
        debug!(target: "tau", "TaskInfo::set_title()");
        self.title = title.into();
    }

    pub fn set_desc(&mut self, desc: &str) {
        debug!(target: "tau", "TaskInfo::set_desc()");
        self.desc = desc.into();
    }

    pub fn set_tags(&mut self, tags: &[String]) {
        debug!(target: "tau", "TaskInfo::set_tags()");
        for tag in tags.iter() {
            let stripped = &tag[1..];
            if tag.starts_with('+') && !self.tags.contains(&stripped.to_string()) {
                self.tags.push(stripped.to_string());
            }
            if tag.starts_with('-') {
                self.tags.retain(|tag| tag != stripped);
            }
        }
    }

    pub fn set_assign(&mut self, assigns: &[String]) {
        debug!(target: "tau", "TaskInfo::set_assign()");
        // self.assign = assigns.to_owned();
        for assign in assigns.iter() {
            let stripped = assign.split('@').collect::<Vec<&str>>()[1];
            if assign.starts_with('@') && !self.assign.contains(&stripped.to_string()) {
                self.assign.push(stripped.to_string());
            }
            if assign.starts_with("-@") {
                self.assign.retain(|assign| assign != stripped);
            }
        }
    }

    pub fn set_project(&mut self, projects: &[String]) {
        debug!(target: "tau", "TaskInfo::set_project()");
        projects.clone_into(&mut self.project);
    }

    pub fn set_comment(&mut self, c: Comment) {
        debug!(target: "tau", "TaskInfo::set_comment()");
        self.comments.push(c);
    }

    pub fn set_rank(&mut self, r: Option<f32>) {
        debug!(target: "tau", "TaskInfo::set_rank()");
        self.rank = r;
    }

    pub fn set_due(&mut self, d: Option<Timestamp>) {
        debug!(target: "tau", "TaskInfo::set_due()");
        self.due = d;
    }

    pub fn set_state(&mut self, state: &str) {
        debug!(target: "tau", "TaskInfo::set_state()");
        if self.get_state() == state {
            return
        }
        self.state = state.to_string();
    }
}