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
use crate::{Command, Reminder, Task};
use chrono::Local;
use chrono_humanize::HumanTime;
use std::env;
use std::fmt;
use std::fs;
use std::io::{self, Read, Write};
use std::process;
use termion::color;
use termion::terminal_size;
static VERSION: &str = "0.4.2";
#[derive(Default)]
pub struct Mind {
    tasks: Vec<Task>,
    reminders: Vec<Reminder>,
    focused: Option<usize>,
}
impl Mind {
    pub fn from(tasks: Vec<Task>, reminders: Vec<Reminder>) -> Self {
        Self {
            tasks,
            reminders,
            focused: None,
        }
    }
    fn push(&mut self, name: String) {
        if let Some((_task, idx)) = self
            .tasks
            .iter()
            .zip(0..)
            .filter(|(task, _idx)| task.name().trim() == name.trim())
            .next()
        {
            let task = self.tasks.remove(idx);
            self.tasks.push(task);
        } else {
            self.tasks.push(Task::new(name));
        }
    }
    fn pop(&mut self) -> Option<Task> {
        self.tasks.pop()
    }
    
    pub fn version() -> &'static str {
        VERSION
    }
    
    pub fn tasks(&self) -> &Vec<Task> {
        &self.tasks
    }
    
    pub fn reminders(&self) -> &Vec<Reminder> {
        &self.reminders
    }
    
    pub fn focused(&self) -> Option<&Task> {
        self.focused
            .map(|idx| self.tasks.get(idx).map(|t| Some(t)).unwrap_or(None))
            .unwrap_or(None)
    }
    
    pub fn remind_tasks(&mut self) {
        let now = Local::now();
        let mut new_reminders: Vec<Reminder> = Vec::new();
        for reminder in self.reminders.clone() {
            if reminder.when() > &now {
                new_reminders.push(reminder);
                continue;
            }
            self.push(format!("📆 {}", &reminder.name().clone()));
            if let Some(next) = reminder.next() {
                let mut next = next;
                while next.when().clone() <= now {
                    next = next.next().unwrap();
                }
                new_reminders.push(next);
            }
        }
        self.reminders = new_reminders;
    }
    fn edit(&mut self, index: usize) -> io::Result<()> {
        let task = self.tasks.get_mut(index).expect("invalid index");
        let path = env::temp_dir().join("___mind___tmp_task___.md");
        {
            let mut file = fs::File::create(&path)?;
            write!(file, "{}", task)?;
        }
        process::Command::new(env::var("EDITOR").unwrap_or("vi".into()))
            .arg(&path)
            .status()
            .expect("failed to open editor");
        let mut contents = String::new();
        fs::File::open(&path)?.read_to_string(&mut contents)?;
        let mut lines = contents.lines();
        let name = lines.next().expect("missing the task name");
        lines.next();
        let details = lines.collect::<String>();
        let details = details.trim();
        task.edit(
            name.into(),
            if details.chars().count() > 0 {
                Some(details.into())
            } else {
                None
            },
        );
        fs::remove_file(path)
    }
    
    pub fn act(&mut self, command: Command) {
        self.focused = None;
        match command {
            Command::Push(name) => {
                self.push(name);
            }
            Command::Continue(index) => {
                if index < self.tasks.len() {
                    let task = self.tasks.remove(index);
                    self.tasks.push(task);
                }
            }
            Command::Get(index) => {
                if index < self.tasks.len() {
                    self.focused = Some(index);
                }
            }
            Command::GetLast => {
                if self.tasks.len() > 0 {
                    self.focused = Some(self.tasks.len() - 1);
                }
            }
            Command::Pop(index) => {
                if index < self.tasks.len() {
                    self.tasks.remove(index);
                }
            }
            Command::PopLast => {
                self.pop();
            }
            Command::Edit(index) => {
                if index < self.tasks.len() {
                    self.edit(index).expect("failed to edit");
                }
            }
            Command::EditLast => {
                if self.tasks.len() > 0 {
                    self.edit(self.tasks.len() - 1).expect("failed to edit");
                }
            }
        }
    }
}
impl fmt::Display for Mind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut color = 155 as u8;
        let len = self.tasks.len();
        let max_name_width = terminal_size().expect("failed to get terminal size").0 as usize - 30;
        let width = self
            .tasks
            .iter()
            .map(|t| t.name().chars().count().min(max_name_width))
            .max()
            .unwrap_or(0);
        let now = Local::now();
        for (task, idx) in self.tasks.iter().zip(0..) {
            let name = task.name().chars().take(max_name_width);
            write!(
                f,
                "[{}] {}{:width$}{}\t{}{}",
                idx,
                color::Fg(color::Rgb(color - 70, color - 30, color)),
                name.collect::<String>(),
                color::Fg(color::Rgb(color - 50, color - 50, color - 50)),
                &HumanTime::from(*task.start() - now),
                color::Fg(color::Reset),
                width = width
            )?;
            if let Some(focused) = self.focused {
                if focused == idx {
                    writeln!(f)?;
                    write!(f, "{}", &task)?;
                }
            }
            if idx < len - 1 {
                writeln!(f)?
            }
            color += 100 as u8 / len as u8;
        }
        Ok(())
    }
}