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
use crate::profile::{DEFAULT_MIC_PROFILE_NAME, DEFAULT_PROFILE_NAME};
use anyhow::{Context, Result};
use log::{error};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::{create_dir_all, File};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Debug, Clone)]
pub struct SettingsHandle {
    path: PathBuf,
    settings: Arc<RwLock<Settings>>,
}

impl SettingsHandle {
    pub async fn load(path: PathBuf, data_dir: &Path) -> Result<SettingsHandle> {
        let mut settings = Settings::read(&path)?.unwrap_or_else(|| Settings {
            profile_directory: Some(data_dir.join("profiles")),
            mic_profile_directory: Some(data_dir.join("mic-profiles")),
            samples_directory: Some(data_dir.join("samples")),
            devices: Default::default(),
        });

        // Set these values if they're missing from the configuration
        if settings.profile_directory.is_none() {
            settings.profile_directory = Some(data_dir.join("profiles"));
        }

        if settings.mic_profile_directory.is_none() {
            settings.mic_profile_directory = Some(data_dir.join("mic-profiles"));
        }

        if settings.samples_directory.is_none() {
            settings.samples_directory = Some(data_dir.join("samples"));
        }


        let handle = SettingsHandle {
            path,
            settings: Arc::new(RwLock::new(settings)),
        };
        handle.save().await;
        Ok(handle)
    }

    pub async fn save(&self) {
        let settings = self.settings.write().await;
        if let Err(e) = settings.write(&self.path) {
            error!(
                "Couldn't save settings to {}: {}",
                self.path.to_string_lossy(),
                e
            );
        }
    }

    pub async fn get_profile_directory(&self) -> PathBuf {
        let settings = self.settings.read().await;
        settings.profile_directory.clone().unwrap()
    }

    pub async fn get_mic_profile_directory(&self) -> PathBuf {
        let settings = self.settings.read().await;
        settings.mic_profile_directory.clone().unwrap()
    }

    pub async fn get_samples_directory(&self) -> PathBuf {
        let settings = self.settings.read().await;
        settings.samples_directory.clone().unwrap()
    }


    pub async fn get_device_profile_name(&self, device_serial: &str) -> Option<String> {
        let settings = self.settings.read().await;
        settings
            .devices
            .get(device_serial)
            .map(|d| d.profile.clone())
    }

    pub async fn get_device_mic_profile_name(&self, device_serial: &str) -> Option<String> {
        let settings = self.settings.read().await;
        settings
            .devices
            .get(device_serial)
            .map(|d| d.mic_profile.clone())
    }

    pub async fn get_device_bleep_volume(&self, device_serial: &str) -> Option<i8> {
        let settings = self.settings.read().await;
        settings.
            devices
            .get(device_serial)
            .map(|d| d.bleep_volume)
    }

    pub async fn set_device_profile_name(&self, device_serial: &str, profile_name: &str) {
        let mut settings = self.settings.write().await;
        let entry = settings
            .devices
            .entry(device_serial.to_owned())
            .or_insert_with(|| DeviceSettings::default());
        entry.profile = profile_name.to_owned();
    }

    pub async fn set_device_mic_profile_name(&self, device_serial: &str, mic_profile_name: &str) {
        let mut settings = self.settings.write().await;
        let entry = settings
            .devices
            .entry(device_serial.to_owned())
            .or_insert_with(|| DeviceSettings::default());
        entry.mic_profile = mic_profile_name.to_owned();
    }

    pub async fn set_device_bleep_volume(&self, device_serial: &str, bleep_volume: i8) {
        let mut settings = self.settings.write().await;
        let entry = settings
            .devices
            .entry(device_serial.to_owned())
            .or_insert_with(|| DeviceSettings::default());
        entry.bleep_volume = bleep_volume;
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Settings {
    profile_directory: Option<PathBuf>,
    mic_profile_directory: Option<PathBuf>,
    samples_directory: Option<PathBuf>,
    devices: HashMap<String, DeviceSettings>,
}

impl Settings {
    pub fn read(path: &Path) -> Result<Option<Settings>> {
        match File::open(path) {
            Ok(reader) => Ok(Some(serde_json::from_reader(reader).context(format!(
                "Could not parse daemon settings file at {}",
                path.to_string_lossy()
            ))?)),
            Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error).context(format!(
                "Could not open daemon settings file for reading at {}",
                path.to_string_lossy()
            )),
        }
    }

    pub fn write(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            if let Err(e) = create_dir_all(parent) {
                if e.kind() != ErrorKind::AlreadyExists {
                    return Err(e).context(format!(
                        "Could not create settings directory at {}",
                        parent.to_string_lossy()
                    ))?;
                }
            }
        }
        let writer = File::create(path).context(format!(
            "Could not open daemon settings file for writing at {}",
            path.to_string_lossy()
        ))?;
        serde_json::to_writer_pretty(writer, self).context(format!(
            "Could not write to daemon settings file at {}",
            path.to_string_lossy()
        ))?;
        Ok(())
    }
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(default)]
struct DeviceSettings {
    profile: String,
    mic_profile: String,
    bleep_volume: i8,
}

impl Default for DeviceSettings {
    fn default() -> Self {
        DeviceSettings {
            profile: DEFAULT_PROFILE_NAME.to_owned(),
            mic_profile: DEFAULT_MIC_PROFILE_NAME.to_owned(),
            bleep_volume: -20,
        }
    }
}