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
use std::path::PathBuf;
use tokio::fs::create_dir_all;
use tokio::io::AsyncWriteExt;
use tokio::{fs::File, io::AsyncReadExt};

use serde::{self, Deserialize, Serialize};
use toml;

#[cfg(target_family = "windows")]
use std::env;

#[cfg(target_family = "unix")]
use xdg;

use crate::errors::AppResult;

pub async fn write_file(path: PathBuf, contents: &str) -> AppResult<()> {
    let mut file = File::create(path).await?;
    file.write_all(contents.as_bytes()).await?;
    Ok(())
}

#[cfg(target_family = "windows")]
fn get_home_directory() -> String {
    env::var("USERPROFILE")
        .ok()
        .expect("Cannot find the env var USERPROFILE")
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Config {
    pub db: Db,
    pub leetcode: Leetcode,
    pub solutions_dir: PathBuf,
}

impl Default for Config {
    fn default() -> Self {
        let solutions_dir = Self::get_default_solutions_dir().expect("Cannot config base dir");
        Self {
            db: Default::default(),
            leetcode: Default::default(),
            solutions_dir,
        }
    }
}

impl Config {
    #[cfg(target_family = "windows")]
    pub fn get_config_base_directory() -> AppResult<PathBuf> {
        let mut home = PathBuf::new();
        home.push(get_home_directory());
        home.push(Self::get_base_name());
        Ok(home)
    }

    #[cfg(target_family = "windows")]
    pub fn get_data_base_directory() -> AppResult<PathBuf> {
        Self::get_config_base_directory()
    }

    #[cfg(target_family = "unix")]
    pub fn get_config_base_directory() -> AppResult<PathBuf> {
        Ok(xdg::BaseDirectories::with_prefix(Self::get_base_name())?.get_config_home())
    }

    #[cfg(target_family = "unix")]
    pub fn get_data_base_directory() -> AppResult<PathBuf> {
        Ok(xdg::BaseDirectories::with_prefix(Self::get_base_name())?.get_data_home())
    }

    pub fn get_base_name() -> &'static str {
        "leetcode_tui"
    }

    pub fn get_default_solutions_dir() -> AppResult<PathBuf> {
        let mut path = Self::get_config_base_directory()?;
        path.push("solutions");
        Ok(path)
    }

    pub async fn create_solutions_dir() -> AppResult<()> {
        let default = Self::get_default_solutions_dir()?;
        Ok(create_dir_all(default).await?)
    }

    pub fn get_config_base_file() -> AppResult<PathBuf> {
        let mut base_config_dir = Self::get_config_base_directory()?;
        base_config_dir.push("config.toml");
        Ok(base_config_dir)
    }

    pub async fn read_config(path: PathBuf) -> AppResult<Self> {
        let mut f = File::open(path).await?;
        let mut contents = String::new();
        f.read_to_string(&mut contents).await?;
        Ok(toml::from_str(contents.as_str())?)
    }

    pub async fn write_config(&self, path: PathBuf) -> AppResult<()> {
        create_dir_all(
            path.parent()
                .unwrap_or_else(|| panic!("Cannot get parent dir of: {}", path.display())),
        )
        .await?;
        write_file(path, toml::to_string(self)?.as_str()).await?;
        Ok(())
    }
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Db {
    pub url: String,
}

impl Db {
    pub fn get_base_sqlite_data_path() -> AppResult<PathBuf> {
        let mut db_path = Config::get_data_base_directory()?;
        db_path.push("data.sqlite");
        Ok(db_path)
    }

    pub async fn touch_default_db() -> AppResult<()> {
        let path = Self::get_base_sqlite_data_path()?;
        create_dir_all(
            path.clone()
                .parent()
                .expect("cannot get the parent directory"),
        )
        .await?;
        write_file(path, "").await?;
        Ok(())
    }
}

impl Default for Db {
    fn default() -> Self {
        Self {
            url: format!(
                "sqlite://{}",
                Self::get_base_sqlite_data_path()
                    .expect("cannot place sqlite data file")
                    .display()
            ),
        }
    }
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Leetcode {
    #[serde(rename = "LEETCODE_SESSION")]
    pub leetcode_session: String,
    pub csrftoken: String,
}

impl Default for Leetcode {
    fn default() -> Self {
        Self {
            leetcode_session: "".to_owned(),
            csrftoken: "".to_owned(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        let sample_config = [
            "solutions_dir = '/some/xyz/path'",
            "[db]",
            "url = 'sqlite://leetcode.sqlite'",
            "[leetcode]",
            "csrftoken = 'ctoken'",
            "LEETCODE_SESSION = 'lsession'",
        ]
        .join("\n");

        let mut pathbuf = PathBuf::new();
        pathbuf.push("/");
        pathbuf.push("some");
        pathbuf.push("xyz");
        pathbuf.push("path");
        let config: Config = toml::from_str(sample_config.as_str()).unwrap();
        assert_eq!(config.solutions_dir, pathbuf);
        assert_eq!(config.leetcode.csrftoken, "ctoken".to_string());
        assert_eq!(config.leetcode.leetcode_session, "lsession".to_string());

        assert_eq!(config.db.url, "sqlite://leetcode.sqlite".to_string());
    }
}