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
use anyhow::{bail, Result};
use copypasta::{ClipboardContext, ClipboardProvider};

use std::{
    fs::File,
    io::{BufRead, BufReader, Write},
};

use std::env;

use clap::{Parser, Subcommand};

use crate::get_save_file_path;
#[derive(Parser)]
#[command(author = env!("CARGO_PKG_AUTHORS"), version = env!("CARGO_PKG_VERSION"), about, long_about = None)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Add a new block to the scratchpad
    Add {
        /// Name of the block to be added
        name: String,
        /// Contents to be associated with the named block
        content: Option<String>,
    },
    /// List all of the blocks within your thoth scratchpad
    List,
    /// Delete a block by name
    Delete {
        /// The name of the block to be deleted
        name: String,
    },
    /// View (STDOUT) the contents of the block by name
    View {
        /// The name of the block to be used
        name: String,
    },
    /// Copy the contents of a block to the system clipboard
    Copy {
        /// The name of the block to be used
        name: String,
    },
}

pub fn add_block(name: &str, content: &str) -> Result<()> {
    let mut file = std::fs::OpenOptions::new()
        .append(true)
        .create(true)
        .open(get_save_file_path())?;

    writeln!(file, "# {}", name)?;
    writeln!(file, "{}", content)?;
    writeln!(file)?;

    println!("Block '{}' added successfully.", name);
    Ok(())
}

pub fn list_blocks() -> Result<()> {
    let file = File::open(get_save_file_path())?;
    let reader = BufReader::new(file);

    for line in reader.lines() {
        let line = line?;

        if let Some(strip) = line.strip_prefix("# ") {
            println!("{}", strip);
        }
    }

    Ok(())
}

pub fn view_block(name: &str) -> Result<()> {
    let file = File::open(get_save_file_path())?;
    let reader = BufReader::new(file);
    let mut blocks = Vec::new();
    let mut current_block = Vec::new();
    let mut current_name = String::new();

    for line in reader.lines() {
        let line = line?;
        if let Some(strip) = line.strip_prefix("# ") {
            if !current_name.is_empty() {
                blocks.push((current_name, current_block));
                current_block = Vec::new();
            }
            current_name = strip.to_string();
        } else {
            current_block.push(line);
        }
    }

    if !current_name.is_empty() {
        blocks.push((current_name, current_block));
    }

    for (block_name, block_content) in blocks {
        if block_name == name {
            for line in block_content {
                println!("{}", line);
            }
        }
    }
    Ok(())
}

pub fn copy_block(name: &str) -> Result<()> {
    let file = File::open(get_save_file_path())?;
    let reader = BufReader::new(file);
    let mut blocks = Vec::new();
    let mut current_block = Vec::new();
    let mut current_name = String::new();
    let mut matched_name: Option<String> = None;

    for line in reader.lines() {
        let line = line?;
        if let Some(strip) = line.strip_prefix("# ") {
            if !current_name.is_empty() {
                blocks.push((current_name, current_block));
                current_block = Vec::new();
            }
            current_name = strip.to_string();
        } else {
            current_block.push(line);
        }
    }

    if !current_name.is_empty() {
        blocks.push((current_name, current_block));
    }

    for (block_name, block_content) in blocks {
        if block_name == name {
            let result_ctx = ClipboardContext::new();

            if result_ctx.is_err() {
                bail!("Failed to create clipboard context for copy block");
            }

            let mut ctx = result_ctx.unwrap();

            let is_success = ctx.set_contents(block_content.join("\n"));

            if is_success.is_err() {
                bail!(format!(
                    "Failed to copy contents of block {} to system clipboard",
                    block_name
                ));
            }
            matched_name = Some(block_name);
        }
    }
    match matched_name {
        Some(name) => println!("Successfully copied contents from block {}", name),
        None => println!("Didn't find the block. Please try again. You can use `thoth list` to find the name of all blocks")
    };

    Ok(())
}

pub fn delete_block(name: &str) -> Result<()> {
    let file = File::open(get_save_file_path())?;
    let reader = BufReader::new(file);
    let mut blocks = Vec::new();
    let mut current_block = Vec::new();
    let mut current_name = String::new();

    for line in reader.lines() {
        let line = line?;
        if let Some(strip) = line.strip_prefix("# ") {
            if !current_name.is_empty() {
                blocks.push((current_name, current_block));
                current_block = Vec::new();
            }
            current_name = strip.to_string();
        } else {
            current_block.push(line);
        }
    }

    if !current_name.is_empty() {
        blocks.push((current_name, current_block));
    }

    let mut file = File::create(get_save_file_path())?;
    let mut deleted = false;

    for (block_name, block_content) in blocks {
        if block_name != name {
            writeln!(file, "# {}", block_name)?;
            for line in block_content {
                writeln!(file, "{}", line)?;
            }
            writeln!(file)?;
        } else {
            deleted = true;
        }
    }

    if deleted {
        println!("Block '{}' deleted successfully.", name);
    } else {
        println!("Block '{}' not found.", name);
    }

    Ok(())
}