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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use std::{
    collections::{hash_map::Entry, HashMap},
    fmt::Display,
    fs::{self},
    io::Cursor,
    path::{Path, PathBuf},
    sync::Arc,
    time::SystemTime,
};

use anyhow::Context;
use binrw::{BinRead, BinReaderExt};
use itertools::Itertools;
use parking_lot::RwLock;
use rayon::prelude::*;
use rustc_hash::FxHashMap;
use tracing::{debug_span, error, info};

use crate::{
    d2_shared::PackageNamedTagEntry,
    oodle,
    package::{Package, PackageVersion, UEntryHeader},
    tag::TagHash64,
    TagHash,
};

#[derive(Clone)]
pub struct HashTableEntryShort {
    pub hash32: TagHash,
    pub reference: TagHash,
}

pub struct PackageManager {
    pub package_dir: PathBuf,
    pub package_paths: FxHashMap<u16, PackagePath>,
    pub version: PackageVersion,

    /// Every entry
    pub package_entry_index: FxHashMap<u16, Vec<UEntryHeader>>,
    pub hash64_table: HashMap<u64, HashTableEntryShort>,
    pub named_tags: Vec<PackageNamedTagEntry>,

    /// Packages that are currently open for reading
    pkgs: RwLock<FxHashMap<u16, Arc<dyn Package>>>,
}

impl PackageManager {
    pub fn new<P: AsRef<Path>>(
        packages_dir: P,
        version: PackageVersion,
    ) -> anyhow::Result<PackageManager> {
        // All the latest packages
        let mut packages: FxHashMap<u16, String> = Default::default();

        let oo2core_3_path = packages_dir.as_ref().join("../bin/x64/oo2core_3_win64.dll");
        let oo2core_9_path = packages_dir.as_ref().join("../bin/x64/oo2core_9_win64.dll");

        if oo2core_3_path.exists() {
            let mut o = oodle::OODLE_3.write();
            if o.is_none() {
                *o = oodle::Oodle::from_path(oo2core_3_path).ok();
            }
        }

        if oo2core_9_path.exists() {
            let mut o = oodle::OODLE_9.write();
            if o.is_none() {
                *o = oodle::Oodle::from_path(oo2core_9_path).ok();
            }
        }

        let build_new_cache = if let Some(cache) = Self::read_package_cache(false) {
            info!("Loading package cache");
            if let Some(p) = cache.versions.get(&version.id()) {
                let timestamp = fs::metadata(&packages_dir)
                    .ok()
                    .and_then(|m| {
                        Some(
                            m.modified()
                                .ok()?
                                .duration_since(SystemTime::UNIX_EPOCH)
                                .ok()?
                                .as_secs(),
                        )
                    })
                    .unwrap_or(0);

                if p.timestamp < timestamp {
                    info!("Detected package directory changes, rebuilding cache");

                    true
                } else {
                    packages = p.paths.clone();
                    false
                }
            } else {
                true
            }
        } else {
            true
        };

        if build_new_cache {
            info!("Creating new package cache for {}", version.id());
            let path = packages_dir.as_ref();
            // Every package in the given directory, including every patch
            let mut packages_all = vec![];
            debug_span!("Discover packages in directory").in_scope(|| -> anyhow::Result<()> {
                for entry in fs::read_dir(path)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.is_file() && path.to_string_lossy().to_lowercase().ends_with(".pkg") {
                        packages_all.push(path.to_string_lossy().to_string());
                    }
                }

                Ok(())
            })?;

            packages_all.sort();

            debug_span!("Filter latest packages").in_scope(|| {
                for p in packages_all {
                    let parts: Vec<&str> = p.split('_').collect();
                    if let Some(Ok(pkg_id)) = parts
                        .get(parts.len() - 2)
                        .map(|s| u16::from_str_radix(s, 16))
                    {
                        packages.insert(pkg_id, p);
                    } else {
                        let _span = debug_span!("Open package to find package ID").entered();
                        // Take the long route and extract the package ID from the header
                        if let Ok(pkg) = version.open(&p) {
                            if pkg.language().english_or_none() {
                                packages.insert(pkg.pkg_id(), p);
                            }
                        }
                    }
                }
            });
        }

        let mut s = Self {
            package_dir: packages_dir.as_ref().to_path_buf(),
            package_paths: packages
                .into_iter()
                .map(|(id, p)| (id, PackagePath::parse_with_defaults(&p)))
                .collect(),
            version,
            package_entry_index: Default::default(),
            hash64_table: Default::default(),
            pkgs: Default::default(),
            named_tags: Default::default(),
        };

        if build_new_cache {
            s.write_package_cache().ok();
        }

        s.build_lookup_tables();

        Ok(s)
    }

    #[cfg(feature = "ignore_package_cache")]
    fn read_package_cache(silent: bool) -> Option<PathCache> {
        use tracing::warn;

        if !silent {
            warn!("Not loading tag cache: ignore_package_cache is enabled")
        }
        None
    }

    #[cfg(feature = "ignore_package_cache")]
    fn write_package_cache(&self) -> anyhow::Result<()> {
        Ok(())
    }

    #[cfg(not(feature = "ignore_package_cache"))]
    fn read_package_cache(silent: bool) -> Option<PathCache> {
        use tracing::warn;

        let cache: Option<PathCache> = serde_json::from_reader(
            std::fs::File::open(exe_relative_path("package_cache.json")).ok()?,
        )
        .ok();

        if let Some(ref c) = cache {
            if c.cache_version != PathCache::default().cache_version {
                if !silent {
                    warn!("Package cache is outdated, building a new one");
                }
                return None;
            }
        }

        cache
    }

    #[cfg(not(feature = "ignore_package_cache"))]
    fn write_package_cache(&self) -> anyhow::Result<()> {
        let mut cache = Self::read_package_cache(true).unwrap_or_default();

        let timestamp = fs::metadata(&self.package_dir)
            .ok()
            .and_then(|m| {
                Some(
                    m.modified()
                        .ok()?
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .ok()?
                        .as_secs(),
                )
            })
            .unwrap_or(0);

        let version = self.version.id();
        let entry = cache.versions.entry(version.clone()).or_default();
        entry.timestamp = timestamp;
        entry.paths.clear();

        for (id, path) in &self.package_paths {
            entry.paths.insert(*id, path.path.clone());
        }

        Ok(std::fs::write(
            exe_relative_path("package_cache.json"),
            serde_json::to_string_pretty(&cache)?,
        )?)
    }

    pub fn build_lookup_tables(&mut self) {
        let tables: Vec<_> = self
            .package_paths
            .par_iter()
            .filter_map(|(_, p)| {
                let _span = debug_span!("Read package tables", package = p.path).entered();
                let pkg = match self.version.open(&p.path) {
                    Ok(package) => package,
                    Err(e) => {
                        error!("Failed to open package '{}': {e}", p.filename);
                        return None;
                    }
                };
                let entries = (pkg.pkg_id(), pkg.entries().to_vec());

                let hashes = pkg
                    .hash64_table()
                    .iter()
                    .map(|h| {
                        (
                            h.hash64,
                            HashTableEntryShort {
                                hash32: h.hash32,
                                reference: h.reference,
                            },
                        )
                    })
                    .collect::<Vec<(u64, HashTableEntryShort)>>();

                let named_tags = pkg.named_tags();

                Some((entries, hashes, named_tags))
            })
            .collect();

        let (entries, hashes, named_tags): (_, Vec<_>, Vec<_>) = tables.into_iter().multiunzip();

        self.package_entry_index = entries;
        self.hash64_table = hashes.into_iter().flatten().collect();
        self.named_tags = named_tags.into_iter().flatten().collect();

        info!("Loaded {} packages", self.package_entry_index.len());
    }

    pub fn get_all_by_reference(&self, reference: u32) -> Vec<(TagHash, UEntryHeader)> {
        self.package_entry_index
            .par_iter()
            .map(|(p, e)| {
                e.iter()
                    .enumerate()
                    .filter(|(_, e)| e.reference == reference)
                    .map(|(i, e)| (TagHash::new(*p, i as _), e.clone()))
                    .collect::<Vec<(TagHash, UEntryHeader)>>()
            })
            .flatten()
            .collect()
    }

    pub fn get_all_by_type(&self, etype: u8, esubtype: Option<u8>) -> Vec<(TagHash, UEntryHeader)> {
        self.package_entry_index
            .par_iter()
            .map(|(p, e)| {
                e.iter()
                    .enumerate()
                    .filter(|(_, e)| {
                        e.file_type == etype
                            && esubtype.map(|t| t == e.file_subtype).unwrap_or(true)
                    })
                    .map(|(i, e)| (TagHash::new(*p, i as _), e.clone()))
                    .collect::<Vec<(TagHash, UEntryHeader)>>()
            })
            .flatten()
            .collect()
    }

    fn get_or_load_pkg(&self, pkg_id: u16) -> anyhow::Result<Arc<dyn Package>> {
        Ok(match self.pkgs.write().entry(pkg_id) {
            Entry::Occupied(o) => o.get().clone(),
            Entry::Vacant(v) => {
                let package_path = self
                    .package_paths
                    .get(&pkg_id)
                    .with_context(|| format!("Couldn't get a path for package id {pkg_id:04x}"))?;

                v.insert(self.version.open(&package_path.path).with_context(|| {
                    format!("Failed to open package '{}'", package_path.filename)
                })?)
                .clone()
            }
        })
    }

    pub fn read_tag(&self, tag: impl Into<TagHash>) -> anyhow::Result<Vec<u8>> {
        let tag = tag.into();
        Ok(self
            .get_or_load_pkg(tag.pkg_id())?
            .read_entry(tag.entry_index() as _)?
            .to_vec())
    }

    pub fn read_tag64(&self, hash: impl Into<TagHash64>) -> anyhow::Result<Vec<u8>> {
        let hash = hash.into();
        let tag = self
            .hash64_table
            .get(&hash.0)
            .context("Hash not found")?
            .hash32;
        self.read_tag(tag)
    }

    pub fn get_entry(&self, tag: impl Into<TagHash>) -> Option<UEntryHeader> {
        let tag: TagHash = tag.into();

        self.package_entry_index
            .get(&tag.pkg_id())?
            .get(tag.entry_index() as usize)
            .cloned()
    }

    pub fn get_named_tag(&self, name: &str, class_hash: u32) -> Option<TagHash> {
        self.named_tags
            .iter()
            .find(|n| n.name == name && n.class_hash == class_hash)
            .map(|n| n.hash)
    }

    pub fn get_named_tags_by_class(&self, class_hash: u32) -> Vec<(String, TagHash)> {
        self.named_tags
            .iter()
            .filter(|n| n.class_hash == class_hash)
            .map(|n| (n.name.clone(), n.hash))
            .collect()
    }

    /// Find the name of a tag by its hash, if it has one.
    pub fn get_tag_name(&self, tag: impl Into<TagHash>) -> Option<String> {
        let tag: TagHash = tag.into();
        self.named_tags
            .iter()
            .find(|n| n.hash == tag)
            .map(|n| n.name.clone())
    }

    /// Read any BinRead type
    pub fn read_tag_binrw<'a, T: BinRead>(&self, tag: impl Into<TagHash>) -> anyhow::Result<T>
    where
        T::Args<'a>: Default + Clone,
    {
        let tag = tag.into();
        let data = self.read_tag(tag)?;
        let mut cursor = Cursor::new(&data);
        Ok(cursor.read_type(self.version.endian())?)
    }

    /// Read any BinRead type
    pub fn read_tag64_binrw<'a, T: BinRead>(&self, hash: impl Into<TagHash64>) -> anyhow::Result<T>
    where
        T::Args<'a>: Default + Clone,
    {
        let data = self.read_tag64(hash)?;
        let mut cursor = Cursor::new(&data);
        Ok(cursor.read_type(self.version.endian())?)
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
pub(crate) struct PathCache {
    cache_version: usize,
    versions: HashMap<String, PathCacheEntry>,
}

#[derive(serde::Serialize, serde::Deserialize, Default)]
pub(crate) struct PathCacheEntry {
    /// Timestamp of the packages directory
    timestamp: u64,
    paths: FxHashMap<u16, String>,
}

impl Default for PathCache {
    fn default() -> Self {
        PathCache {
            cache_version: 2,
            versions: Default::default(),
        }
    }
}

#[cfg(not(feature = "ignore_package_cache"))]
fn exe_directory() -> PathBuf {
    std::env::current_exe()
        .unwrap()
        .parent()
        .unwrap()
        .to_path_buf()
}

#[cfg(not(feature = "ignore_package_cache"))]
fn exe_relative_path(path: &str) -> PathBuf {
    exe_directory().join(path)
}

#[derive(Debug, Clone)]
pub struct PackagePath {
    /// eg. ps3, w64
    pub platform: String,
    /// eg. arch_fallen, dungeon_prophecy, europa
    pub name: String,

    /// eg. 0059, 043c, unp1, unp2
    pub id: String,
    pub patch: u8,

    /// Full path to the package
    pub path: String,
    pub filename: String,
}

impl PackagePath {
    /// Example path: ps3_arch_fallen_0059_0.pkg
    pub fn parse(path: &str) -> Option<Self> {
        let path_filename = Path::new(path).file_name()?.to_string_lossy();
        let parts: Vec<&str> = path_filename.split('_').collect();
        if parts.len() < 4 {
            return None;
        }

        let platform = parts[0].to_string();
        let name = parts[1..parts.len() - 2].join("_");
        let id = parts[parts.len() - 2].to_string();
        let patch = parts[parts.len() - 1].split('.').next()?.parse().ok()?;

        Some(Self {
            platform,
            name,
            id,
            patch,
            path: path.to_string(),
            filename: path_filename.to_string(),
        })
    }

    pub fn parse_with_defaults(path: &str) -> Self {
        let path_filename = Path::new(path)
            .file_name()
            .map_or(path.to_string(), |p| p.to_string_lossy().to_string());
        Self::parse(path).unwrap_or_else(|| Self {
            platform: "unknown".to_string(),
            name: "unknown".to_string(),
            id: "unknown".to_string(),
            patch: 0,
            path: path.to_string(),
            filename: path_filename,
        })
    }
}

impl Display for PackagePath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.filename)
    }
}