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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
#![warn(missing_docs)]

//! # Typed bindings to `CDClient.fdb`
//!
//! This crate provides typed bindings to an FDB file that follows the structure of
//! `CDClient.fdb` from the 1.10.64 client. The design goals are:
//!
//! - Make writing code that uses this API as easy as possible
//! - Enable serialization with the [`serde`](https://serde.rs) crate
//! - Accept FDBs that may have additional columns and tables

use std::fmt;

use assembly_core::buffer::CastError;
use assembly_fdb::{
    mem::{Field, Row, Table, Tables},
    value::Value,
};
use latin1str::Latin1Str;

include!(concat!(env!("OUT_DIR"), "/generated.rs"));

pub mod ext;

use columns::{IconsColumn, MissionTasksColumn, MissionsColumn};
use tables::{
    ActivitiesTable, ActivityRewardsTable, ActivityTextTable, BehaviorParameterTable,
    BehaviorTemplateTable, CollectibleComponentTable, ComponentsRegistryTable,
    CurrencyDenominationsTable, DeletionRestrictionsTable, DestructibleComponentTable, EmotesTable,
    IconsTable, InventoryComponentTable, ItemComponentTable, ItemSetSkillsTable, ItemSetsTable,
    JetPackPadComponentTable, LootMatrixTable, LootTableTable, MissionEmailTable,
    MissionNpcComponentTable, MissionTasksTable, MissionTextTable, MissionsTable, NpcIconsTable,
    ObjectSkillsTable, ObjectsTable, PackageComponentTable, PlayerStatisticsTable,
    PreconditionsTable, PropertyTemplateTable, RebuildComponentTable, RebuildSectionsTable,
    RenderComponentTable, RewardCodesTable, RewardsTable, SkillBehaviorTable,
    SmashableComponentTable, SpeedchatMenuTable, TamingBuildPuzzlesTable, UgBehaviorSoundsTable,
    VendorComponentTable, WhatsCoolItemSpotlightTable, WhatsCoolNewsAndTipsTable,
    ZoneLoadingTipsTable, ZoneTableTable,
};

use self::ext::{Components, Mission, MissionTask};

/// ## A "typed" database row
///
/// A typed table is the combination of a "raw" table from the `assembly_fdb` crate with
/// some metadata. Examples for this metadata are:
///
/// - Mapping from a well-known column name (e.g. `MissionID`) to the "real" column index within the FDB
pub trait TypedTable<'de>: Sized {
    /// The type representing one well-known column
    type Column: TypedColumn;
    /// The literal name of the table
    const NAME: &'static str;

    /// Return the contained "raw" table
    fn as_raw(&self) -> Table<'de>;
    /// Create a typed table from a raw table.
    ///
    /// This function constructs the necessary metadata.
    fn new(inner: Table<'de>) -> Self;

    /// Get an instance from a database
    fn of(tables: Tables<'de>) -> Option<Result<Self, CastError>> {
        let table = tables.by_name(Self::NAME)?;
        Some(table.map(Self::new))
    }
}

/// ## A "typed" database row
///
/// A typed row is the combination of a "raw" row from the `assembly_fdb crate with the typing information
/// given in [`TypedRow::Table`].
pub trait TypedRow<'a, 'b>
where
    'a: 'b,
{
    /// The table this row belongs to
    type Table: TypedTable<'a> + 'a;

    /// Creates a new "typed" row from a "typed" table and a "raw" row
    fn new(inner: Row<'a>, table: &'b Self::Table) -> Self;

    /// Get a specific entry from the row by unique ID
    ///
    /// The `index_key` is the value of the first column, the `key` is the value of the unique ID column
    /// and the `id_col` must be the "real" index of that unique ID column.
    fn get(table: &'b Self::Table, index_key: i32, key: i32, id_col: usize) -> Option<Self>
    where
        Self: Sized,
    {
        let hash = index_key as usize % table.as_raw().bucket_count();
        if let Some(b) = table.as_raw().bucket_at(hash) {
            for r in b.row_iter() {
                if r.field_at(id_col).and_then(|x| x.into_opt_integer()) == Some(key) {
                    return Some(Self::new(r, table));
                }
            }
        }
        None
    }
}

/// # A column type for a table
pub trait TypedColumn: fmt::Debug + Copy + Clone + Eq {
    /// Return the original name of the column
    fn to_static_str(&self) -> &'static str;
    /// Serialize a field to a struct
    fn serialize_struct_field<S: ::serde::ser::SerializeStruct>(
        &self,
        s: &mut S,
        value: Field,
    ) -> Result<(), S::Error>;
}

/// # Iterator over [`TypedRow`]s
///
/// This class is used to iterate over typed rows
pub struct RowIter<'a, 'b, R>
where
    R: TypedRow<'a, 'b>,
{
    inner: assembly_fdb::mem::iter::TableRowIter<'a>,
    table: &'b R::Table,
}

impl<'a, 'b, R> RowIter<'a, 'b, R>
where
    R: TypedRow<'a, 'b>,
{
    /// Create a new row iter from a typed table
    pub fn new(table: &'b R::Table) -> Self {
        Self {
            inner: table.as_raw().row_iter(),
            table,
        }
    }
}

impl<'a, 'b, R> Iterator for RowIter<'a, 'b, R>
where
    R: TypedRow<'a, 'b>,
{
    type Item = R;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|row| R::new(row, self.table))
    }
}

#[derive(Clone)]
/// A selection of relevant database tables
pub struct TypedDatabase<'db> {
    /// Activities
    pub activities: ActivitiesTable<'db>,
    /// ActivityText
    pub activity_text: ActivityTextTable<'db>,
    /// ActivityRewards
    pub activity_rewards: Option<ActivityRewardsTable<'db>>,
    /// BehaviorParameter
    pub behavior_parameters: BehaviorParameterTable<'db>,
    /// BehaviorTemplate
    pub behavior_templates: BehaviorTemplateTable<'db>,
    /// CollectibleComponent
    pub collectible_component: CollectibleComponentTable<'db>,
    /// ComponentRegistry
    pub comp_reg: ComponentsRegistryTable<'db>,
    /// CurrencyDenominations
    pub currency_denominations: CurrencyDenominationsTable<'db>,
    /// DeletionRestrictions
    pub deletion_restrictions: DeletionRestrictionsTable<'db>,
    /// DestructibleComponent
    pub destructible_component: DestructibleComponentTable<'db>,
    /// Emotes
    pub emotes: EmotesTable<'db>,
    /// Icons
    pub icons: IconsTable<'db>,
    /// InventoryComponent
    pub inventory_component: InventoryComponentTable<'db>,
    /// ItemComponent
    pub item_component: ItemComponentTable<'db>,
    /// ItemSets
    pub item_sets: ItemSetsTable<'db>,
    /// ItemSetSkills
    pub item_set_skills: ItemSetSkillsTable<'db>,
    /// JetPackPadComponent
    pub jet_pack_pad_component: Option<JetPackPadComponentTable<'db>>,
    /// LootTable
    pub loot_table: LootTableTable<'db>,
    /// LootMatrix
    pub loot_matrix: LootMatrixTable<'db>,
    /// MissionEmail
    pub mission_email: Option<MissionEmailTable<'db>>,
    /// MissionNPCComponent
    pub mission_npc_component: Option<MissionNpcComponentTable<'db>>,
    /// MissionTasks
    pub mission_tasks: MissionTasksTable<'db>,
    /// MissionText
    pub mission_text: MissionTextTable<'db>,
    /// Missions
    pub missions: MissionsTable<'db>,
    /// NpcIcons
    pub npc_icons: NpcIconsTable<'db>,
    /// Objects
    pub objects: ObjectsTable<'db>,
    /// Objects
    pub object_skills: ObjectSkillsTable<'db>,
    /// PackageComponent
    pub package_component: Option<PackageComponentTable<'db>>,
    /// PlayerStatistics
    pub player_statistics: Option<PlayerStatisticsTable<'db>>,
    /// Preconditions
    pub preconditions: PreconditionsTable<'db>,
    /// PropertyTemplate
    pub property_template: PropertyTemplateTable<'db>,
    /// RebuildComponent
    pub rebuild_component: RebuildComponentTable<'db>,
    /// RebuildSections
    pub rebuild_sections: Option<RebuildSectionsTable<'db>>,
    /// Rewards
    pub rewards: Option<RewardsTable<'db>>,
    /// RewardCodes
    pub reward_codes: Option<RewardCodesTable<'db>>,
    /// RenderComponent
    pub render_comp: RenderComponentTable<'db>,
    /// SkillBehavior
    pub skills: SkillBehaviorTable<'db>,
    /// SmashableComponent
    pub smashable_component: Option<SmashableComponentTable<'db>>,
    /// SpeedchatMenu
    pub speedchat_menu: SpeedchatMenuTable<'db>,
    /// TamingBuildPuzzles
    pub taming_build_puzzles: TamingBuildPuzzlesTable<'db>,
    /// UGBehaviorSounds
    pub ug_behavior_sounds: Option<UgBehaviorSoundsTable<'db>>,
    /// VendorComponent
    pub vendor_component: Option<VendorComponentTable<'db>>,
    /// WhatsCoolItemSpotlight
    pub whats_cool_item_spotlight: Option<WhatsCoolItemSpotlightTable<'db>>,
    /// WhatsCoolNewsAndTips
    pub whats_cool_news_and_tips: Option<WhatsCoolNewsAndTipsTable<'db>>,
    /// ZoneLoadingTips
    pub zone_loading_tips: Option<ZoneLoadingTipsTable<'db>>,
    /// ZoneTable
    pub zone_table: ZoneTableTable<'db>,
}

fn is_not_empty(s: &&Latin1Str) -> bool {
    !s.is_empty()
}

impl<'a> TypedDatabase<'a> {
    /// Construct a new typed database
    pub fn new(tables: Tables<'a>) -> Result<Self, CastError> {
        Ok(TypedDatabase {
            activities: ActivitiesTable::of(tables).expect("Missing Table 'Activities'")?,
            activity_text: ActivityTextTable::of(tables).expect("Missing Table 'ActivityText'")?,
            activity_rewards: ActivityRewardsTable::of(tables).transpose()?,
            behavior_parameters: BehaviorParameterTable::of(tables)
                .expect("Missing Table 'BehaviorParameter'")?,
            behavior_templates: BehaviorTemplateTable::of(tables)
                .expect("Missing Table 'BehaviorTemplate'")?,
            collectible_component: CollectibleComponentTable::of(tables)
                .expect("Missing Table 'CollectibleComponent'")?,
            comp_reg: ComponentsRegistryTable::of(tables)
                .expect("Missing Table 'ComponentsRegistry'")?,
            currency_denominations: CurrencyDenominationsTable::of(tables)
                .expect("Missing Table 'CurrencyDenominations'")?,
            deletion_restrictions: DeletionRestrictionsTable::of(tables)
                .expect("Missing Table 'DeletionRestrictions'")?,
            destructible_component: DestructibleComponentTable::of(tables)
                .expect("Missing Table 'DestructibleComponent'")?,
            emotes: EmotesTable::of(tables).expect("Missing Table 'Emotes'")?,
            icons: IconsTable::of(tables).expect("Missing Table 'Icons'")?,
            inventory_component: InventoryComponentTable::of(tables)
                .expect("Missing Table 'InventoryComponent'")?,
            item_component: ItemComponentTable::of(tables)
                .expect("Missing Table 'ItemComponent'")?,
            item_sets: ItemSetsTable::of(tables).expect("Missing Table 'ItemSets'")?,
            item_set_skills: ItemSetSkillsTable::of(tables)
                .expect("Missing Table 'ItemSetSkills'")?,
            jet_pack_pad_component: JetPackPadComponentTable::of(tables).transpose()?,
            loot_matrix: LootMatrixTable::of(tables).expect("Missing Table 'LootMatrix'")?,
            loot_table: LootTableTable::of(tables).expect("Missing Table 'LootTable'")?,
            mission_email: MissionEmailTable::of(tables).transpose()?,
            mission_npc_component: MissionNpcComponentTable::of(tables).transpose()?,
            mission_tasks: MissionTasksTable::of(tables).expect("Missing Table 'MissionTasks'")?,
            mission_text: MissionTextTable::of(tables).expect("Missing Table 'MissionText'")?,
            missions: MissionsTable::of(tables).expect("Missing Table 'Missions'")?,
            npc_icons: NpcIconsTable::of(tables).expect("Missing Table 'NpcIcons'")?,
            objects: ObjectsTable::of(tables).expect("Missing Table 'Objects'")?,
            object_skills: ObjectSkillsTable::of(tables).expect("Missing Table 'ObjectSkills'")?,
            package_component: PackageComponentTable::of(tables).transpose()?,
            player_statistics: PlayerStatisticsTable::of(tables).transpose()?,
            preconditions: PreconditionsTable::of(tables)
                .expect("Missing Table 'Preconditions'")?,
            property_template: PropertyTemplateTable::of(tables)
                .expect("Missing Table 'PropertyTemplate'")?,
            rewards: RewardsTable::of(tables).transpose()?,
            reward_codes: RewardCodesTable::of(tables).transpose()?,
            rebuild_component: RebuildComponentTable::of(tables)
                .expect("Missing Table 'RebuildComponent'")?,
            rebuild_sections: RebuildSectionsTable::of(tables).transpose()?,
            render_comp: RenderComponentTable::of(tables)
                .expect("Missing Table 'RenderComponent'")?,
            skills: SkillBehaviorTable::of(tables).expect("Missing Table 'SkillBehavior'")?,
            smashable_component: SmashableComponentTable::of(tables).transpose()?,
            speedchat_menu: SpeedchatMenuTable::of(tables)
                .expect("Missing Table 'SpeedchatMenu'")?,
            taming_build_puzzles: TamingBuildPuzzlesTable::of(tables)
                .expect("Missing Table 'TamingBuildPuzzles'")?,
            ug_behavior_sounds: UgBehaviorSoundsTable::of(tables).transpose()?,
            vendor_component: VendorComponentTable::of(tables).transpose()?,
            whats_cool_item_spotlight: WhatsCoolItemSpotlightTable::of(tables).transpose()?,
            whats_cool_news_and_tips: WhatsCoolNewsAndTipsTable::of(tables).transpose()?,
            zone_loading_tips: ZoneLoadingTipsTable::of(tables).transpose()?,
            zone_table: ZoneTableTable::of(tables).expect("Missing Table 'ZoneTable'")?,
        })
    }

    /// Get the path of an icon ID
    pub fn get_icon_path(&self, id: i32) -> Option<&Latin1Str> {
        let hash = u32::from_ne_bytes(id.to_ne_bytes());
        let bucket = self.icons.as_raw().bucket_for_hash(hash);

        let col_icon_path = self
            .icons
            .get_col(IconsColumn::IconPath)
            .expect("Missing column 'Icons::IconPath'");

        for row in bucket.row_iter() {
            let id_field = row.field_at(0).unwrap();

            if id_field == Field::Integer(id) {
                return row.field_at(col_icon_path).unwrap().into_opt_text();
            }
        }
        None
    }

    /// Get data for the specified mission ID
    pub fn get_mission_data(&self, id: i32) -> Option<Mission> {
        let hash = u32::from_ne_bytes(id.to_ne_bytes());
        let bucket = self.missions.as_raw().bucket_for_hash(hash);

        let col_mission_icon_id = self
            .missions
            .get_col(MissionsColumn::MissionIconId)
            .expect("Missing column 'Missions::mission_icon_id'");
        let col_is_mission = self
            .missions
            .get_col(MissionsColumn::IsMission)
            .expect("Missing column 'Missions::is_mission'");

        for row in bucket.row_iter() {
            let id_field = row.field_at(0).unwrap();

            if id_field == Field::Integer(id) {
                let mission_icon_id = row
                    .field_at(col_mission_icon_id)
                    .unwrap()
                    .into_opt_integer();
                let is_mission = row
                    .field_at(col_is_mission)
                    .unwrap()
                    .into_opt_boolean()
                    .unwrap_or(true);

                return Some(Mission {
                    mission_icon_id,
                    is_mission,
                });
            }
        }
        None
    }

    /// Get a list of mission tasks for the specified mission ID
    pub fn get_mission_tasks(&self, id: i32) -> Vec<MissionTask> {
        let hash = u32::from_ne_bytes(id.to_ne_bytes());
        let bucket = self.mission_tasks.as_raw().bucket_for_hash(hash);
        let mut tasks = Vec::with_capacity(4);

        let col_icon_id = self
            .mission_tasks
            .get_col(MissionTasksColumn::IconId)
            .expect("Missing column 'MissionTasks::icon_id'");
        let col_uid = self
            .mission_tasks
            .get_col(MissionTasksColumn::Uid)
            .expect("Missing column 'MissionTasks::uid'");

        for row in bucket.row_iter() {
            let id_field = row.field_at(0).unwrap();

            if id_field == Field::Integer(id) {
                let icon_id = row.field_at(col_icon_id).unwrap().into_opt_integer();
                let uid = row.field_at(col_uid).unwrap().into_opt_integer().unwrap();

                tasks.push(MissionTask { icon_id, uid })
            }
        }
        tasks
    }

    /// Get the name and description for the specified LOT
    pub fn get_object_name_desc(&self, id: i32) -> Option<(String, String)> {
        let hash = u32::from_ne_bytes(id.to_ne_bytes());

        let table = self.objects.as_raw();
        let bucket = table
            .bucket_at(hash as usize % table.bucket_count())
            .unwrap();

        for row in bucket.row_iter() {
            let mut fields = row.field_iter();
            let id_field = fields.next().unwrap();
            if id_field == Field::Integer(id) {
                let name = fields.next().unwrap(); // 1: name
                let description = fields.nth(2).unwrap(); // 4: description
                let display_name = fields.nth(2).unwrap(); // 7: displayName
                let internal_notes = fields.nth(2).unwrap(); // 10: internalNotes

                let title = match (
                    name.into_opt_text().filter(is_not_empty),
                    display_name.into_opt_text().filter(is_not_empty),
                ) {
                    (Some(name), Some(display)) if display != name => {
                        format!("{} ({}) | Object #{}", display.decode(), name.decode(), id)
                    }
                    (Some(name), _) => {
                        format!("{} | Object #{}", name.decode(), id)
                    }
                    (None, Some(display)) => {
                        format!("{} | Object #{}", display.decode(), id)
                    }
                    (None, None) => {
                        format!("Object #{}", id)
                    }
                };
                let desc = match (
                    description.into_opt_text().filter(is_not_empty),
                    internal_notes.into_opt_text().filter(is_not_empty),
                ) {
                    (Some(description), Some(internal_notes)) if description != internal_notes => {
                        format!("{} ({})", description.decode(), internal_notes.decode(),)
                    }
                    (Some(description), _) => {
                        format!("{}", description.decode())
                    }
                    (None, Some(internal_notes)) => {
                        format!("{}", internal_notes.decode())
                    }
                    (None, None) => String::new(),
                };
                return Some((title, desc));
            }
        }
        None
    }

    /// Get the path of the icon asset of the specified render component
    pub fn get_render_image(&self, id: i32) -> Option<&Latin1Str> {
        let hash = u32::from_ne_bytes(id.to_ne_bytes());
        let table = self.render_comp.as_raw();
        let bucket = table
            .bucket_at(hash as usize % table.bucket_count())
            .unwrap();

        for row in bucket.row_iter() {
            let mut fields = row.field_iter();
            let id_field = fields.next().unwrap();
            if id_field == Field::Integer(id) {
                let _render_asset = fields.next().unwrap();
                let icon_asset = fields.next().unwrap();

                if let Field::Text(url) = icon_asset {
                    return Some(url);
                }
            }
        }
        None
    }

    /// Get all components for the specified LOT
    pub fn get_components(&self, id: i32) -> Components {
        let hash = u32::from_ne_bytes(id.to_ne_bytes());
        let table = self.comp_reg.as_raw();
        let bucket = table
            .bucket_at(hash as usize % table.bucket_count())
            .unwrap();

        let mut comp = Components::default();

        for row in bucket.row_iter() {
            let mut fields = row.field_iter();
            let id_field = fields.next().unwrap();
            if id_field == Field::Integer(id) {
                let component_type = fields.next().unwrap();
                let component_id = fields.next().unwrap();

                if let Value::Integer(2) = component_type {
                    comp.render = component_id.into_opt_integer();
                }
            }
        }
        comp
    }
}