aboutsummaryrefslogtreecommitdiffstats
path: root/src/state/threads.rs
blob: 4248d93184178606ec2209836f08c22cab17b903 (plain) (blame)
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
use crate::db;
use super::State;

use notmuch::DatabaseMode;
use std::io::Write;
use termion::{color, event::Key};

pub struct Threads {
    pub threads: Vec<Thread>,
    pub i: isize,
}

pub struct Thread {
    subject: String,
    authors: Vec<String>,
    _id: String,
    messages: Vec<String>,
}

impl Thread {
    pub fn remove_tag(&self, tag: &str) {
        let db = db::open(DatabaseMode::ReadWrite).unwrap();
        for m_id in self.messages.iter() {
            db
                .find_message(m_id)
                .unwrap()
                .unwrap()
                .remove_tag(tag)
                .unwrap();
        }
    }
}

impl<'d, 'q> Threads {
    pub fn new(threads: notmuch::Threads<'d, 'q>) -> Self {
        let threads = threads.map(|t| Thread {
            subject: t.subject().to_string(),
            authors: t.authors().clone(),
            _id: t.id().to_string(),
            messages: t.messages().map(|m| m.id().to_string()).collect(),
        }).collect();

        Self {
            threads,
            i: 0
        }
    }

    pub fn init<W: Write>(&mut self, out: &mut W) {
        draw(&self, out);
    }

    pub fn tick<W: Write>(mut self, out: &mut W, key: Key) -> State {
        match key {
            Key::Char('j') => self.i += 1,
            Key::Char('k') => self.i -= 1,
            Key::Char('i') => {
                self.threads[self.i as usize].remove_tag("inbox");
            }
            _ => (),
        }
        self.i = self.i.rem_euclid(self.threads.len() as isize);
        draw(&self, out);
        State::Threads(self)
    }
}

fn draw<W: Write>(state: &Threads, out: &mut W) {
    write!(out, "{}", termion::clear::All).unwrap();

    for (i, thread) in state.threads.iter().enumerate() {
        write!(out, "{}", termion::cursor::Goto(1, (i + 1) as u16)).unwrap();
        let highlight = i == state.i as usize;
        if highlight {
            write!(out, "{}", color::Fg(color::Red)).unwrap();
        }
        write!(out, "thread {:?}, {:?}", thread.subject, thread.authors).unwrap();
        if highlight {
            write!(out, "{}", color::Fg(color::Reset)).unwrap();
        }
    }
    out.flush().unwrap();
}