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
use std::convert::Infallible;

use crate::{
    cli::LastCmd as Cmd,
    cli::LastResCmd as ResCmd,
    history::{self, History},
    Ctx, QuartzResult,
};

pub fn cmd(ctx: &Ctx, maybe_command: Option<Cmd>) -> QuartzResult<(), Infallible> {
    let entry = History::last(ctx).expect("no history found");

    if maybe_command.is_none() {
        println!("{entry}");
        return Ok(());
    }

    if let Some(command) = maybe_command {
        match command {
            Cmd::Handle => println!("{}", entry.handle()),
            Cmd::Req => req(&entry),
            Cmd::Res { command } => res(command, &entry),
        }
    };

    Ok(())
}

pub fn req(entry: &history::Entry) {
    req_head(entry);
}

pub fn req_head(entry: &history::Entry) {
    let iter = entry
        .messages()
        .iter()
        .filter_map(|p| match p.starts_with('>') {
            true => Some(
                p.split('\n')
                    .map(|s| s.trim_start_matches('>').trim())
                    .collect::<Vec<&str>>()
                    .join("\n"),
            ),
            false => None,
        });

    for m in iter {
        println!("{m}");
    }
}

pub fn res(command: Option<ResCmd>, entry: &history::Entry) {
    if let Some(command) = command {
        match command {
            ResCmd::Head => res_head(entry),
            ResCmd::Body => res_body(entry),
        }
    } else {
        res_head(entry);
        res_body(entry);
    }
}

pub fn res_head(entry: &history::Entry) {
    let iter = entry
        .messages()
        .iter()
        .filter_map(|p| match p.starts_with('<') {
            true => Some(
                p.split('\n')
                    .map(|s| s.trim_start_matches('<').trim())
                    .collect::<Vec<&str>>()
                    .join("\n"),
            ),
            false => None,
        });

    for m in iter {
        println!("{m}");
    }
}

pub fn res_body(entry: &history::Entry) {
    if let Some(body) = entry.messages().last() {
        println!("{}", body);
    }
}