~jshsj/rust_todo

ref: 7c8f9a09d0d463be5ca55632212a2cf1acea71cc rust_todo/src/tasks.rs -rw-r--r-- 3.9 KiB
7c8f9a09Joshua push wip 1 year, 9 months ago
                                                                                
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
use serde;
use serde::{Serialize, Deserialize};
use serde_json;
use chrono::{DateTime, Utc, TimeZone};
use std::fmt;
use std::fs::{read_dir, File};

use failure::Error;

static PATH_PREFIX: &str = "./tasks/";

#[derive(Serialize, Deserialize, Debug)]
pub struct Task {
    pub name: String,
    pub path: String,
    pub sub_tasks: Vec<SubTask>,
    pub done: bool,
    pub due_date: Option<DateTime<Utc>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SubTask {
    pub name: String,
    pub done: bool,
    pub due_date: Option<DateTime<Utc>>,
}


impl Task {
    fn new(name: String, due_date: Option<DateTime<Utc>>) -> Result<Task, Error> {
        let path = convert_name_to_path(&name);
        let t = Task {
            name,
            path,
            sub_tasks: Vec::<SubTask>::new(),
            done: false,
            due_date,
        };
        t.save()?;
        Ok(t)
    }

    fn add_subtask(&mut self, name: String, due_date: Option<DateTime<Utc>>) -> Result<(), Error> {
        self.sub_tasks.push(SubTask::new(name, due_date));
        self.save()?;
        Ok(())
    }

    fn save(&self) -> Result<(), Error> {
        let file = File::create(format!("{}{}", PATH_PREFIX, self.path))
            .expect("Couldn't create file");
        serde_json::to_writer(file, &self)?;
        Ok(())
    }
}

impl SubTask {
    fn new(name: String, due_date: Option<DateTime<Utc>>) -> SubTask {
        SubTask {
            name,
            done: false,
            due_date,
        }
    }
}

impl fmt::Display for Task {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl fmt::Display for SubTask {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

pub struct TaskManager {
    tasklist: Vec<Task>
}

impl TaskManager {
    pub fn new() -> TaskManager {
        let mut t = TaskManager {
            tasklist: Vec::<Task>::new()
        };
        t.init();
        t
    }

    pub fn add_task(&mut self, name: String) -> Result<(), Error> {
        self.tasklist.push(Task::new(name, None)?);
        Ok(())
    }

    pub fn add_task_with_date(&mut self, name: String, due_date: DateTime<Utc>) -> Result<(), Error> {
        self.tasklist.push(Task::new(name, Some(due_date))?);
        Ok(())
    }

    pub fn add_subtask_to_task(&mut self, task_name: String, subtask_name: String) -> Result<(),Error> {
        let mut task = self.get_task_by_name(task_name)?;
        task.add_subtask(subtask_name, None)?;
        Ok(())

    }

    pub fn get_task_by_name(&mut self, task_name: String) -> Result<Task, Error> {
        let filtered: Vec<Task> = self.tasklist.as_ref().into_iter().filter(|t| t.name == task_name).collect();
        if filtered.is_empty() {
            bail!("No Item founds")
        }
        Ok(filtered[0])
    }

    pub fn all_tasks(&mut self) -> &Vec<Task> {
        &self.tasklist
    }

    fn init(&mut self) {
        let task_files = read_task_files();
        for task_file in task_files {
            //let t: Vec<&str> = task_file.split("/").collect();
            //let path = String::from(t[2]);
            &self.load_task(task_file);
        }
    }

    fn load_task(&mut self, path: String) {
        let file = File::open(&path).unwrap();
        let task: Task = serde_json::from_reader(file)
            .expect(format!("Can't parse file {}", path).as_str());
        self.tasklist.push(task);
    }
}

//HELPERS

fn convert_name_to_path(name: &str) -> String {
    let lowercase = name.to_lowercase();
    let lowercase: Vec<&str> = lowercase.split(" ").collect();

    lowercase.join("_")
}

fn convert_path_to_name(path: &str) -> String {
    String::from("test")
}

fn read_task_files() -> Vec<String> {
    let files = read_dir("./tasks").expect("directory doesn't exist");
    let mut task_files = Vec::<String>::new();

    for file in files {
        task_files.push(String::from(file.unwrap().path().to_str().unwrap()));
    }

    task_files
}