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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! Path identifier for a Glacier Resource file.
//!
//! ResourceID represents a resource identifier with utility methods for manipulating and extracting information from the identifier.
//! The identifier is expected to follow a specific format: ` [protocol:path/to/file.extension(parameters).platform_extension] `
//! The parameter can be optional. A ResourceID can also be nested/derived
//! ### Examples of valid ResourceID
//! ```txt
//! [assembly:/images/sprites/player.jpg](asspritesheet).pc_jpeg
//! [[assembly:/images/sprites/player.jpg](asspritesheet).pc_jpeg].pc_png
//! ```

use crate::resource::runtime_resource_id::RuntimeResourceID;
use std::str::FromStr;
use lazy_regex::regex;
use thiserror::Error;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

static CONSOLE_TAG: &str = "pc";

#[derive(Error, Debug)]
pub enum ResourceIDError {
    #[error("Invalid format {}", _0)]
    InvalidFormat(String),
}

#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ResourceID {
    uri: String,
}

impl FromStr for ResourceID {
    type Err = ResourceIDError;

    fn from_str(source: &str) -> Result<Self, Self::Err> {
        let mut uri = source.to_ascii_lowercase();
        uri.retain(|c| c as u8 > 0x1F);
        let rid = Self { uri };

        if !rid.is_valid() {
            return Err(ResourceIDError::InvalidFormat("".to_string()));
        };

        Ok(Self {
            uri: rid.uri.replace(format!("{}_", CONSOLE_TAG).as_str(), ""),
        })
    }
}

impl ResourceID {
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a derived ResourceID from a existing one. This nests the original ResourceID
    /// ```
    /// # use std::str::FromStr;
    /// # use rpkg_rs::misc::resource_id::ResourceID;
    /// # use rpkg_rs::misc::resource_id::ResourceIDError;
    /// # fn main() -> Result<(), ResourceIDError>{
    ///     let resource_id = ResourceID::from_str("[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].pc_fx")?;
    ///     let derived = resource_id.create_derived("dx11", "mate");
    ///     assert_eq!(derived.resource_path(), "[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).pc_mate");
    /// #   Ok(())
    /// # }
    /// ```
    pub fn create_derived(&self, parameters: &str, extension: &str) -> ResourceID {
        let mut derived = format!("[{}]", self.uri);
        if !parameters.is_empty() {
            derived += format!("({})", parameters).as_str();
        }
        derived += ".";
        if !extension.is_empty() {
            derived += extension;
        }

        ResourceID { uri: derived }
    }

    /// Create a ResourceID with aspect parameters
    /// ```
    /// # use std::str::FromStr;
    /// # use rpkg_rs::misc::resource_id::ResourceID;     
    /// # use rpkg_rs::misc::resource_id::ResourceIDError;
    ///
    /// # fn main() -> Result<(), ResourceIDError>{
    ///  
    ///     let resource_id = ResourceID::from_str("[assembly:/templates/aspectdummy.aspect].pc_entitytype")?;
    ///     let sub_id_1 = ResourceID::from_str("[assembly:/_pro/effects/geometry/water.prim].pc_entitytype")?;
    ///     let sub_id_2 = ResourceID::from_str("[modules:/zdisablecameracollisionaspect.class].entitytype")?;
    ///
    ///     let aspect = resource_id.create_aspect(vec![&sub_id_1, &sub_id_2]);
    ///
    ///     assert_eq!(aspect.resource_path(), "[assembly:/templates/aspectdummy.aspect]([assembly:/_pro/effects/geometry/water.prim].entitytype,[modules:/zdisablecameracollisionaspect.class].entitytype).pc_entitytype");
    /// #   Ok(())
    /// # }
    ///
    /// ```
    pub fn create_aspect(&self, ids: Vec<&ResourceID>) -> ResourceID {
        let mut rid = self.clone();
        for id in ids {
            rid.add_parameter(id.uri.as_str());
        }
        rid
    }

    pub fn add_parameter(&mut self, param: &str) {
        let params = self.parameters();
        let new_uri = if params.is_empty() {
            match self.uri.rfind('.') {
                Some(index) => {
                    let mut modified_string = self.uri.to_string();
                    modified_string.insert(index, '(');
                    modified_string.insert_str(index + 1, param);
                    modified_string.insert(index + param.len() + 1, ')');
                    modified_string
                }
                None => self.uri.to_string(), // If no dot found, return the original string
            }
        } else {
            match self.uri.rfind(").") {
                Some(index) => {
                    let mut modified_string = self.uri.to_string();
                    modified_string.insert(index, ',');
                    modified_string.insert_str(index + 1, param);
                    modified_string
                }
                None => self.uri.to_string(), // If no dot found, return the original string
            }
        };
        self.uri = new_uri;
    }

    /// Get the resource path.
    /// Will append the platform tag
    pub fn resource_path(&self) -> String {
        let mut platform_uri = String::new();

        if let Some(dot) = self.uri.rfind('.') {
            platform_uri.push_str(&self.uri[..=dot]);
            platform_uri.push_str("pc_");
            platform_uri.push_str(&self.uri[dot + 1..]);
            platform_uri
        } else {
            self.uri.clone()
        }
    }

    /// Get the base ResourceID within a derived ResourceID
    /// ```
    /// # use std::str::FromStr;
    /// # use rpkg_rs::misc::resource_id::ResourceID;
    /// # use rpkg_rs::misc::resource_id::ResourceIDError;
    /// # fn main() -> Result<(), ResourceIDError>{
    ///     let resource_id = ResourceID::from_str("[[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).mate](dx12).pc_mate")?;
    ///     let inner_most_path = resource_id.inner_most_resource_path();
    ///     assert_eq!(inner_most_path.resource_path(), "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].pc_fx");
    /// #    Ok(())
    /// # }
    /// ```
    pub fn inner_most_resource_path(&self) -> ResourceID {
        let open_count = self.uri.chars().filter(|c| *c == '[').count();
        if open_count == 1 {
            return self.clone();
        }

        let parts = self.uri.splitn(open_count + 1, ']').collect::<Vec<&str>>();
        let rid_str = format!("{}]{}", parts[0], parts[1])
            .chars()
            .skip(open_count - 1)
            .collect::<String>();

        match Self::from_str(rid_str.as_str()) {
            Ok(r) => r,
            Err(_) => self.clone(),
        }
    }

    /// Get the base ResourceID within a derived ResourceID
    /// ```
    /// # use std::str::FromStr;
    /// # use rpkg_rs::misc::resource_id::ResourceID;
    /// # use rpkg_rs::misc::resource_id::ResourceIDError;
    /// # fn main() -> Result<(), ResourceIDError>{
    ///  
    ///     let resource_id = ResourceID::from_str("[[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).mate](dx12).pc_mate")?;
    ///     let inner_path = resource_id.inner_resource_path();
    ///
    ///     assert_eq!(inner_path.resource_path(), "[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).pc_mate");
    /// #   Ok(())
    /// }
    ///
    /// ```
    pub fn inner_resource_path(&self) -> ResourceID {
        let open_count = self.uri.chars().filter(|c| *c == '[').count();
        if open_count == 1 {
            return self.clone();
        }

        let re = regex!(r"\[(.*?)][^]]*$");
        if let Some(captures) = re.captures(&self.uri) {
            if let Some(inner_string) = captures.get(1) {
                if let Ok(rid) = ResourceID::from_str(inner_string.as_str()) {
                    return rid;
                }
            }
        }
        self.clone()
    }

    pub fn protocol(&self) -> Option<String> {
        match self.uri.find(':') {
            Some(n) => {
                let protocol: String = self.uri.chars().take(n).collect();
                Some(protocol.replace('[', ""))
            }
            None => None,
        }
    }

    pub fn parameters(&self) -> Vec<String> {
        let re = regex!(r"(.*)\((.*)\)\.(.*)");
        if let Some(captures) = re.captures(self.uri.as_str()) {
            if let Some(cap) = captures.get(2) {
                return cap
                    .as_str()
                    .split(',')
                    .map(|s: &str| s.to_string())
                    .collect();
            }
        }
        vec![]
    }

    pub fn path(&self) -> Option<String> {
        let path: String = self.uri.chars().skip(1).collect();
        if let Some(n) = path.rfind('/') {
            let p: String = path.chars().take(n).collect();
            if !p.contains('.') {
                return Some(p);
            }
        }
        None
    }

    pub fn is_empty(&self) -> bool {
        self.uri.is_empty()
    }

    pub fn is_valid(&self) -> bool {
        {
            self.uri.starts_with('[')
                && !self.uri.contains("unknown")
                && !self.uri.contains('*')
                && self.uri.contains(']')
        }
    }

    pub fn into_rrid(self) -> RuntimeResourceID {
        RuntimeResourceID::from_resource_id(&self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_parameters() -> Result<(), ResourceIDError> {
        let mut resource_id = ResourceID::from_str(
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx",
        )?;
        resource_id.add_parameter("lmao");
        assert_eq!(resource_id.resource_path(), "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass](lmao).pc_fx");
        assert_eq!(resource_id.parameters(), ["lmao".to_string()]);

        resource_id.add_parameter("lmao2");
        assert_eq!(resource_id.resource_path(), "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass](lmao,lmao2).pc_fx");
        Ok(())
    }

    #[test]
    fn test_get_inner_most_resource_path() -> Result<(), ResourceIDError> {
        let resource_id = ResourceID::from_str(
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx",
        )?;
        let inner_path = resource_id.inner_most_resource_path();
        assert_eq!(
            inner_path.resource_path(),
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].pc_fx"
        );

        let resource_id = ResourceID::from_str("[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).mate")?;
        let inner_path = resource_id.inner_most_resource_path();
        assert_eq!(
            inner_path.resource_path(),
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].pc_fx"
        );

        let resource_id = ResourceID::from_str("[[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).mate](dx12).pc_mate")?;
        let inner_path = resource_id.inner_most_resource_path();
        assert_eq!(
            inner_path.resource_path(),
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].pc_fx"
        );

        Ok(())
    }

    #[test]
    fn text_get_inner_resource_path() -> Result<(), ResourceIDError> {
        let resource_id = ResourceID::from_str(
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx",
        )?;
        let inner_path = resource_id.inner_resource_path();
        assert_eq!(
            inner_path.resource_path(),
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].pc_fx"
        );

        let resource_id = ResourceID::from_str("[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).mate")?;
        let inner_path = resource_id.inner_resource_path();
        assert_eq!(
            inner_path.resource_path(),
            "[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].pc_fx"
        );

        let resource_id = ResourceID::from_str("[[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).mate](dx12).pc_mate")?;
        let inner_path = resource_id.inner_resource_path();
        assert_eq!(inner_path.resource_path(), "[[assembly:/_pro/_test/usern/materialclasses/ball_of_water_b.materialclass].fx](dx11).pc_mate");
        Ok(())
    }
}