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
/*
 * Vento, a CLI inventory for your files.
 * Copyright (C) 2022 Lux Aliaga
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

use super::{
    common,
    error::{throw_error, ErrorType},
};
use anyhow::{bail, Result};
use colored::Colorize;
use fs_extra::dir::{move_dir, CopyOptions};
use std::fs;
use std::path::{Path, PathBuf};

/// Takes a file or directory and stores it in an inventory slot
pub fn take(file: &String, slot: &str, message: bool) -> Result<()> {
    let ventodir = &common::env_config()?.vento_dir;

    if !ventodir.is_dir() {
        // Detects if Vento hasn't been initialized and bails if so
        throw_error(ErrorType::NotInitialized)?;
    };
    let slotdir: PathBuf = match slot {
        "active" | "a" => common::env_config()?.active_dir,
        "inactive" | "i" => common::env_config()?.inactive_dir,
        _ => PathBuf::new(),
    };

    if !slotdir.is_dir() {
        // Detects if the slot provided exists
        bail!(
            "{}",
            format!(
                "No such slot. Valid slots are {} and {}",
                "active".green().bold(),
                "inactive".blue().bold()
            )
            .red()
        );
    };

    let sourcepath: PathBuf = Path::new(&file).to_path_buf();
    let mut sourcelocation: PathBuf = fs::canonicalize(&sourcepath)?;
    sourcelocation.pop();
    let filename = Path::new(&file).file_name().unwrap().to_str().unwrap();
    let destpath: PathBuf = [&slotdir, &Path::new(&filename).to_path_buf()]
        .iter()
        .collect();

    if Path::exists(&destpath) {
        // Checks if there's a file with the same name in the inventory.
        throw_error(ErrorType::ExistsInventory)?;
    }

    if sourcepath.is_file() | sourcepath.is_symlink() {
        // Checks the path's file type
        fs::copy(file, &destpath)?;
        fs::remove_file(file)?;
    } else if sourcepath.is_dir() {
        let options = CopyOptions::new();
        move_dir(file, &slotdir, &options)?;
    } else {
        throw_error(ErrorType::NoFileOrDir)?;
    }

    common::history(common::HistoryData {
        path: sourcelocation.clone(),
        file: String::from(filename),
        slot: String::from(slot),
        action: common::Action::Take,
    })?;

    if message {
        println!(
            "✅ {} {} {} {} {} {} {}",
            "Took".green(),
            &filename.bold(),
            "from".green(),
            &sourcelocation.to_str().unwrap(),
            "to".green(),
            match slot {
                "active" => slot.green(),
                "inactive" => slot.blue(),
                _ => slot.red(),
            }
            .bold(),
            "slot".green()
        );
    }

    Ok(())
}

/// Drops a file or directory and stores it in an inventory slot
pub fn drop(file: &String, slot: &str, dest: PathBuf, message: bool) -> Result<()> {
    // Drops a file or directory
    let ventodir = &common::env_config()?.vento_dir;

    if !ventodir.is_dir() {
        // Detects if Vento hasn't been initialized and bails if so
        throw_error(ErrorType::NotInitialized)?;
    };

    let slotdir: PathBuf = match slot {
        "active" | "a" => common::env_config()?.active_dir,
        "inactive" | "i" => common::env_config()?.inactive_dir,
        _ => PathBuf::new(),
    };

    if !slotdir.is_dir() {
        // Detects if the slot provided exists
        bail!(
            "{}",
            format!(
                "No such slot. Valid slots are {} and {}",
                "active".green().bold(),
                "inactive".blue().bold()
            )
            .red()
        );
    };

    let sourcepath: PathBuf = [&slotdir, &Path::new(file).to_path_buf()].iter().collect();
    let mut destpath: PathBuf = [
        Path::new(&dest).to_path_buf(),
        Path::new(file).to_path_buf(),
    ]
    .iter()
    .collect();

    if Path::exists(&destpath) {
        // Checks if there's a file with the same name in the destination path.
        throw_error(ErrorType::ExistsDestination)?;
    }

    if sourcepath.is_file() | sourcepath.is_symlink() {
        // Checks the path's file type
        fs::copy(&sourcepath, &destpath)?;
        fs::remove_file(&sourcepath)?;
    } else if sourcepath.is_dir() {
        let destpath: PathBuf = Path::new(&dest).to_path_buf();
        let options = CopyOptions::new();
        move_dir(&sourcepath, destpath, &options)?;
    } else {
        throw_error(ErrorType::NoFileOrDir)?;
    }

    destpath.pop();

    common::history(common::HistoryData {
        path: destpath.clone(),
        file: String::from(file),
        slot: String::from(slot),
        action: common::Action::Drop,
    })?;

    if message {
        println!(
            "✅ {} {} {} {} {} {}",
            "Dropped".green(),
            &file.bold(),
            "from".green(),
            match slot {
                "active" => slot.green(),
                "inactive" => slot.blue(),
                _ => slot.red(),
            }
            .bold(),
            "slot into".green(),
            &destpath.to_str().unwrap()
        );
    };

    Ok(())
}