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

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

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(())
}

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

impl Config {
    pub fn get_base_directory() -> AppResult<BaseDirectories> {
        Ok(xdg::BaseDirectories::with_prefix("leetcode_tui")?)
    }

    pub fn get_base_config() -> AppResult<PathBuf> {
        let config_path = Self::get_base_directory()?.place_config_file("config.toml")?;
        Ok(config_path)
    }

    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<()> {
        write_file(path, toml::to_string(self)?.as_str()).await?;
        Ok(())
    }
}

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

impl Db {
    pub fn get_base_sqlite_data_path() -> AppResult<PathBuf> {
        let base_dirs = Config::get_base_directory()?;
        let data_file_path = base_dirs.place_data_file("data.sqlite")?;
        Ok(data_file_path)
    }

    pub async fn touch_default_db() -> AppResult<()> {
        let path = Self::get_base_sqlite_data_path()?;
        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)]
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 = [
            "[db]",
            "url = 'sqlite://leetcode.sqlite'",
            "[leetcode]",
            "csrftoken = 'ctoken'",
            "LEETCODE_SESSION = 'lsession'",
        ]
        .join("\n");

        let config: Config = toml::from_str(sample_config.as_str()).unwrap();
        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());
    }
}