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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 derivative::Derivative;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;
use wildland_corex::catlib_service::entities::CatlibContainerFilter;
use wildland_corex::catlib_service::error::CatlibError;
use wildland_corex::{
    Container,
    ContainerManager,
    ContainerManagerError,
    CoreXError,
    StorageTemplate,
    StorageTemplateError,
};

use super::cargo_lib::DfsApi;
use super::storage::ContainerStorage;
use crate::multidevice_state::error::MultideviceStateError;
use crate::multidevice_state::user_state::{UserMultideviceState, UserMultideviceStateContext};

#[derive(Debug, Clone)]
pub struct CargoContainerFilter {
    inner: CatlibContainerFilter,
}

impl From<CargoContainerFilter> for CatlibContainerFilter {
    fn from(val: CargoContainerFilter) -> CatlibContainerFilter {
        val.inner
    }
}

impl CargoContainerFilter {
    #[tracing::instrument(level = "trace")]
    pub fn has_exact_path(path: String) -> Self {
        Self {
            inner: CatlibContainerFilter::HasExactPath(path.into()),
        }
    }

    #[tracing::instrument(level = "trace")]
    pub fn has_path_starting_with(path: String) -> Self {
        Self {
            inner: CatlibContainerFilter::HasPathStartingWith(path.into()),
        }
    }

    #[tracing::instrument(level = "trace")]
    pub fn has_uuid(uuid: Uuid) -> Self {
        Self {
            inner: CatlibContainerFilter::HasUuid(uuid),
        }
    }

    #[tracing::instrument(level = "trace")]
    pub fn any(filters: Vec<Self>) -> Self {
        Self {
            inner: CatlibContainerFilter::Any(
                filters.into_iter().map(|elem| elem.into()).collect(),
            ),
        }
    }

    #[tracing::instrument(level = "trace")]
    pub fn or(f1: Self, f2: Self) -> Self {
        Self {
            inner: CatlibContainerFilter::Or(Box::new(f1.into()), Box::new(f2.into())),
        }
    }

    #[tracing::instrument(level = "trace")]
    pub fn and(f1: Self, f2: Self) -> Self {
        Self {
            inner: CatlibContainerFilter::And(Box::new(f1.into()), Box::new(f2.into())),
        }
    }

    #[tracing::instrument(level = "trace")]
    #[allow(clippy::should_implement_trait)]
    pub fn not(f: Self) -> Self {
        Self {
            inner: CatlibContainerFilter::Not(Box::new(f.into())),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum MountState {
    Mounted,
    Unmounted,
    MountedOrUnmounted,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum Persistency {
    GloballyPersistent,
    LocallyPersistent,
}

#[derive(Error, Debug, Clone)]
#[repr(C)]
pub enum AddStorageError {
    #[error("Catlib Error: {0}")]
    CatlibErr(#[from] CatlibError),
    #[error("Storage Template Error: {0}")]
    StorageTemplateError(#[from] StorageTemplateError),
}

/// TODO: CARGO-276 - SharingMessage content and format
///
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SharingMessage {}

#[derive(Derivative, Clone)]
#[derivative(Debug)]
pub struct CargoContainer {
    #[derivative(Debug = "ignore")]
    container_manager: ContainerManager,
    #[derivative(Debug = "ignore")]
    multi_device_state: UserMultideviceState,
    #[derivative(Debug = "ignore")]
    dfs_api: DfsApi,

    corex_container: Container,

    // except for special use cases (like process of encrypting or decrypting) a whole container
    // should have either all storages encrypted or all of them unencrypted from Cargo pov
    encrypted: bool,
}

impl CargoContainer {
    pub fn new(
        container_manager: ContainerManager,
        corex_container: Container,
        encrypted: bool,
        multi_device_state: UserMultideviceState,
        dfs_api: DfsApi,
    ) -> Self {
        Self {
            container_manager,
            corex_container,
            multi_device_state,
            dfs_api,
            encrypted,
        }
    }

    // CargoLib methods

    /// Tries to mount the container.
    ///
    /// # Args:
    /// - persistent_mount - optional argument which can mark a containers as being automatically mounted.
    ///   Containers can be marked as persistent in either global (user's) or local (device's) context.
    ///   Passing `None` value indicates that a container is being mounted temporarily.
    pub fn mount(
        &self,
        persistent_mount: Option<Persistency>,
    ) -> Result<(), ContainerManagerError> {
        self.container_manager.mount(&self.corex_container)?;
        if let Some(persistency) = persistent_mount {
            self.set_persistency(persistency).unwrap_or_else(|err| {
                let container_uuid = self.corex_container.uuid();
                tracing::error!(
                    "Setting container with uuid: {container_uuid} as automounted failed. Reason: {err}"
                )
            })
        };

        Ok(())
    }

    /// Tries to unmount the container.
    ///
    /// # Args:
    /// - persistent_unmount - optional argument which can unset persistency setting, either in global (user's) or local (device's) context.
    ///   Passing `None` value indicates that persistency will not be changed.
    #[tracing::instrument(level = "trace")]
    pub fn unmount(
        &self,
        persistent_unmount: Option<Persistency>,
    ) -> Result<(), ContainerManagerError> {
        self.container_manager.unmount(&self.corex_container)?;
        if let Some(persistency) = persistent_unmount {
            self.unset_persistency(persistency)
                .unwrap_or_else(|err| {
                    let container_uuid = self.uuid();
                    tracing::error!(
                        "Setting container with uuid: {container_uuid} as not automounted failed. Reason: {err}"
                    )
                })
        };
        Ok(())
    }

    #[tracing::instrument(level = "trace")]
    pub fn is_mounted(&self) -> bool {
        self.container_manager.is_mounted(&self.corex_container)
    }

    #[tracing::instrument(level = "trace")]
    fn get_context(&self, persistency: Persistency) -> &UserMultideviceStateContext {
        match persistency {
            Persistency::GloballyPersistent => self.multi_device_state.global_context(),
            Persistency::LocallyPersistent => self.multi_device_state.local_context(),
        }
    }

    /// Checks if the container is set as persistently mounted in one of contexts (global or local)
    ///
    #[tracing::instrument(level = "trace")]
    pub fn is_automounted(&self) -> Result<bool, MultideviceStateError> {
        Ok(self
            .multi_device_state
            .get_automounted_containers()?
            .any(|(uuid, _time)| uuid == self.corex_container.uuid()))
    }

    /// Sets a container as persistently mounted in one of contexts (global or local) specified by the argument.
    ///
    pub fn set_persistency(&self, persistency: Persistency) -> Result<(), MultideviceStateError> {
        self.get_context(persistency)
            .set_container_as_automounted(self.uuid())
    }

    /// Unsets a container as persistently mounted in one of contexts (global or local) specified by the argument.
    ///
    pub fn unset_persistency(&self, persistency: Persistency) -> Result<(), MultideviceStateError> {
        self.get_context(persistency)
            .remove_container_from_automount(self.uuid())
    }

    // Corex methods

    #[tracing::instrument(level = "trace")]
    pub fn get_storages(&self) -> Result<Vec<ContainerStorage>, CoreXError> {
        Ok(self
            .corex_container
            .get_storages()?
            .into_iter()
            .map(|s| ContainerStorage::from_corex_storage(s, self.dfs_api.clone()))
            .collect())
    }

    #[tracing::instrument(level = "trace")]
    pub fn add_storage(
        &mut self,
        storage_template: &StorageTemplate,
    ) -> Result<ContainerStorage, AddStorageError> {
        let storage = self.corex_container.render_template(storage_template)?;

        Ok(self
            .corex_container
            .add_storage(storage_template.catlib_uuid(), storage, self.encrypted)
            .map(|s| ContainerStorage::from_corex_storage(s, self.dfs_api.clone()))?)
    }

    #[tracing::instrument(level = "trace")]
    pub fn remove_storage(&mut self, uuid: &Uuid) -> Result<(), CoreXError> {
        self.corex_container.remove_storage(uuid)
    }

    #[tracing::instrument(level = "trace")]
    pub fn change_path(&self, path: String) -> Result<(), CatlibError> {
        self.corex_container.change_path(path)
    }

    #[tracing::instrument(level = "trace")]
    pub fn get_path(&self) -> Result<String, CatlibError> {
        self.corex_container.get_path()
    }

    #[tracing::instrument(level = "trace")]
    pub fn set_name(&self, new_name: String) -> Result<(), CatlibError> {
        self.corex_container.set_name(new_name)
    }

    #[tracing::instrument(level = "trace")]
    pub fn remove(&self) -> Result<(), CatlibError> {
        self.corex_container.remove()
    }

    #[tracing::instrument(level = "trace")]
    pub fn name(&self) -> Result<String, CatlibError> {
        self.corex_container.name()
    }

    #[tracing::instrument(level = "trace")]
    pub fn uuid(&self) -> Uuid {
        self.corex_container.uuid()
    }
}