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
use std::collections::HashMap;

use bevy_ecs::prelude::*;
use indexmap::IndexMap;
use uuid::Uuid;
pub use valence_generated::attributes::{EntityAttribute, EntityAttributeOperation};
use valence_protocol::packets::play::entity_attributes_s2c::*;
use valence_protocol::Ident;

/// An instance of an Entity Attribute.
#[derive(Component, Clone, PartialEq, Debug)]
pub struct EntityAttributeInstance {
    /// The attribute.
    attribute: EntityAttribute,
    /// The base value of the attribute.
    base_value: f64,
    /// The add modifiers of the attribute.
    add_modifiers: IndexMap<Uuid, f64>,
    /// The multiply base modifiers of the attribute.
    multiply_base_modifiers: IndexMap<Uuid, f64>,
    /// The multiply total modifiers of the attribute.
    multiply_total_modifiers: IndexMap<Uuid, f64>,
}

impl EntityAttributeInstance {
    /// Creates a new instance of an Entity Attribute.
    pub fn new(attribute: EntityAttribute) -> Self {
        Self {
            attribute,
            base_value: attribute.default_value(),
            add_modifiers: IndexMap::new(),
            multiply_base_modifiers: IndexMap::new(),
            multiply_total_modifiers: IndexMap::new(),
        }
    }

    /// Creates a new instance of an Entity Attribute with a value.
    pub fn new_with_value(attribute: EntityAttribute, base_value: f64) -> Self {
        Self {
            attribute,
            base_value,
            add_modifiers: IndexMap::new(),
            multiply_base_modifiers: IndexMap::new(),
            multiply_total_modifiers: IndexMap::new(),
        }
    }

    /// Gets the attribute.
    pub fn attribute(&self) -> EntityAttribute {
        self.attribute
    }

    /// Gets the base value of the attribute.
    pub fn base_value(&self) -> f64 {
        self.base_value
    }

    /// Gets the computed value of the attribute.
    pub fn compute_value(&self) -> f64 {
        let mut value = self.base_value;

        // Increment value by modifier
        for (_, modifier) in &self.add_modifiers {
            value += modifier;
        }

        let v = value;

        // Increment value by modifier * v
        for (_, modifier) in &self.multiply_base_modifiers {
            value += v * modifier;
        }

        // Increment value by modifier * value
        for (_, modifier) in &self.multiply_total_modifiers {
            value += value * modifier;
        }

        value.clamp(self.attribute.min_value(), self.attribute.max_value())
    }

    /// Sets an add modifier.
    ///
    /// If the modifier already exists, it will be overwritten.
    ///
    /// Returns a mutable reference to self.
    pub fn with_add_modifier(&mut self, uuid: Uuid, modifier: f64) -> &mut Self {
        self.add_modifiers.insert(uuid, modifier);
        self
    }

    /// Sets a multiply base modifier.
    ///
    /// If the modifier already exists, it will be overwritten.
    ///
    /// Returns a mutable reference to self.
    pub fn with_multiply_base_modifier(&mut self, uuid: Uuid, modifier: f64) -> &mut Self {
        self.multiply_base_modifiers.insert(uuid, modifier);
        self
    }

    /// Sets a multiply total modifier.
    ///
    /// If the modifier already exists, it will be overwritten.
    ///
    /// Returns a mutable reference to self.
    pub fn with_multiply_total_modifier(&mut self, uuid: Uuid, modifier: f64) -> &mut Self {
        self.multiply_total_modifiers.insert(uuid, modifier);
        self
    }

    /// Sets a value modifier based on the operation.
    ///
    /// If the modifier already exists, it will be overwritten.
    ///
    /// Returns a mutable reference to self.
    pub fn with_modifier(
        &mut self,
        uuid: Uuid,
        modifier: f64,
        operation: EntityAttributeOperation,
    ) -> &mut Self {
        match operation {
            EntityAttributeOperation::Add => self.with_add_modifier(uuid, modifier),
            EntityAttributeOperation::MultiplyBase => {
                self.with_multiply_base_modifier(uuid, modifier)
            }
            EntityAttributeOperation::MultiplyTotal => {
                self.with_multiply_total_modifier(uuid, modifier)
            }
        }
    }

    /// Removes a modifier.
    pub fn remove_modifier(&mut self, uuid: Uuid) {
        self.add_modifiers.swap_remove(&uuid);
        self.multiply_base_modifiers.swap_remove(&uuid);
        self.multiply_total_modifiers.swap_remove(&uuid);
    }

    /// Clears all modifiers.
    pub fn clear_modifiers(&mut self) {
        self.add_modifiers.clear();
        self.multiply_base_modifiers.clear();
        self.multiply_total_modifiers.clear();
    }

    /// Checks if a modifier exists.
    pub fn has_modifier(&self, uuid: Uuid) -> bool {
        self.add_modifiers.contains_key(&uuid)
            || self.multiply_base_modifiers.contains_key(&uuid)
            || self.multiply_total_modifiers.contains_key(&uuid)
    }

    /// Converts to a `TrackedEntityProperty` for use in the
    /// `EntityAttributesS2c` packet.
    pub(crate) fn to_property(&self) -> TrackedEntityProperty {
        TrackedEntityProperty {
            key: self.attribute.name().into(),
            value: self.base_value(),
            modifiers: self
                .add_modifiers
                .iter()
                .map(|(&uuid, &amount)| TrackedAttributeModifier {
                    uuid,
                    amount,
                    operation: 0,
                })
                .chain(self.multiply_base_modifiers.iter().map(|(&uuid, &amount)| {
                    TrackedAttributeModifier {
                        uuid,
                        amount,
                        operation: 1,
                    }
                }))
                .chain(
                    self.multiply_total_modifiers
                        .iter()
                        .map(|(&uuid, &amount)| TrackedAttributeModifier {
                            uuid,
                            amount,
                            operation: 2,
                        }),
                )
                .collect(),
        }
    }
}

/// The attributes of a Living Entity.
#[derive(Component, Clone, PartialEq, Debug, Default)]
pub struct EntityAttributes {
    attributes: HashMap<EntityAttribute, EntityAttributeInstance>,
    recently_changed: Vec<EntityAttribute>,
}

impl EntityAttributes {
    /// Gets and clears the recently changed attributes.
    pub(crate) fn take_recently_changed(&mut self) -> Vec<EntityAttribute> {
        std::mem::take(&mut self.recently_changed)
    }

    /// Marks an attribute as recently changed.
    pub(crate) fn mark_recently_changed(&mut self, attribute: EntityAttribute) {
        if attribute.tracked() && !self.recently_changed.contains(&attribute) {
            self.recently_changed.push(attribute);
        }
    }
}

impl EntityAttributes {
    /// Creates a new instance of `EntityAttributes`.
    pub fn new() -> Self {
        Self {
            attributes: HashMap::new(),
            recently_changed: Vec::new(),
        }
    }

    /// Gets the instance of an attribute.
    pub fn get(&self, attribute: EntityAttribute) -> Option<&EntityAttributeInstance> {
        self.attributes.get(&attribute)
    }

    /// Gets the base value of an attribute.
    ///
    /// Returns [`None`] if the attribute does not exist.
    pub fn get_base_value(&self, attribute: EntityAttribute) -> Option<f64> {
        self.get(attribute).map(|instance| instance.base_value())
    }

    /// Gets the computed value of an attribute.
    ///
    /// Returns [`None`] if the attribute does not exist.
    pub fn get_compute_value(&self, attribute: EntityAttribute) -> Option<f64> {
        self.get(attribute).map(|instance| instance.compute_value())
    }

    /// Checks if an attribute exists.
    pub fn has_attribute(&self, attribute: EntityAttribute) -> bool {
        self.attributes.contains_key(&attribute)
    }

    /// Creates an attribute if it does not exist.
    pub fn create_attribute(&mut self, attribute: EntityAttribute) {
        self.mark_recently_changed(attribute);
        self.attributes
            .entry(attribute)
            .or_insert_with(|| EntityAttributeInstance::new(attribute));
    }

    /// Creates an attribute if it does not exist and sets its base value.
    ///
    /// Returns self.
    ///
    /// ## Note
    ///
    /// Only to be used in builder-like patterns.
    pub(crate) fn with_attribute_and_value(
        mut self,
        attribute: EntityAttribute,
        base_value: f64,
    ) -> Self {
        self.attributes
            .entry(attribute)
            .or_insert_with(|| EntityAttributeInstance::new_with_value(attribute, base_value))
            .base_value = base_value;
        self
    }

    /// Sets the base value of an attribute.
    pub fn set_base_value(&mut self, attribute: EntityAttribute, value: f64) {
        self.mark_recently_changed(attribute);
        self.attributes
            .entry(attribute)
            .or_insert_with(|| EntityAttributeInstance::new(attribute))
            .base_value = value;
    }

    /// Sets an add modifier of an attribute.
    pub fn set_add_modifier(&mut self, attribute: EntityAttribute, uuid: Uuid, modifier: f64) {
        self.mark_recently_changed(attribute);
        self.attributes
            .entry(attribute)
            .or_insert_with(|| EntityAttributeInstance::new(attribute))
            .with_add_modifier(uuid, modifier);
    }

    /// Sets a multiply base modifier of an attribute.
    pub fn set_multiply_base_modifier(
        &mut self,
        attribute: EntityAttribute,
        uuid: Uuid,
        modifier: f64,
    ) {
        self.mark_recently_changed(attribute);
        self.attributes
            .entry(attribute)
            .or_insert_with(|| EntityAttributeInstance::new(attribute))
            .with_multiply_base_modifier(uuid, modifier);
    }

    /// Sets a multiply total modifier of an attribute.
    pub fn set_multiply_total_modifier(
        &mut self,
        attribute: EntityAttribute,
        uuid: Uuid,
        modifier: f64,
    ) {
        self.mark_recently_changed(attribute);
        self.attributes
            .entry(attribute)
            .or_insert_with(|| EntityAttributeInstance::new(attribute))
            .with_multiply_total_modifier(uuid, modifier);
    }

    /// Sets a value modifier of an attribute based on the operation.
    pub fn set_modifier(
        &mut self,
        attribute: EntityAttribute,
        uuid: Uuid,
        modifier: f64,
        operation: EntityAttributeOperation,
    ) {
        self.mark_recently_changed(attribute);
        self.attributes
            .entry(attribute)
            .or_insert_with(|| EntityAttributeInstance::new(attribute))
            .with_modifier(uuid, modifier, operation);
    }

    /// Removes a modifier of an attribute.
    pub fn remove_modifier(&mut self, attribute: EntityAttribute, uuid: Uuid) {
        self.mark_recently_changed(attribute);
        if let Some(instance) = self.attributes.get_mut(&attribute) {
            instance.remove_modifier(uuid);
        }
    }

    /// Clears all modifiers of an attribute.
    pub fn clear_modifiers(&mut self, attribute: EntityAttribute) {
        self.mark_recently_changed(attribute);
        if let Some(instance) = self.attributes.get_mut(&attribute) {
            instance.clear_modifiers();
        }
    }

    /// Checks if a modifier exists on an attribute.
    pub fn has_modifier(&self, attribute: EntityAttribute, uuid: Uuid) -> bool {
        self.attributes
            .get(&attribute)
            .is_some_and(|inst| inst.has_modifier(uuid))
    }

    /// **For internal use only.**
    ///
    /// Converts to a [`Vec`] of [`AttributeProperty`]s.
    pub fn to_properties(&self) -> Vec<AttributeProperty> {
        self.attributes
            .iter()
            .filter(|(_, instance)| instance.attribute().tracked())
            .map(|(_, instance)| instance.to_property().to_property())
            .collect()
    }
}

/// Tracks the attributes of a Living Entity.
#[derive(Component, Clone, Debug, Default)]
pub struct TrackedEntityAttributes {
    /// The attributes that have been modified.
    modified: IndexMap<EntityAttribute, TrackedEntityProperty>,
}

#[derive(Clone, Debug)]
pub(crate) struct TrackedEntityProperty {
    key: String,
    value: f64,
    modifiers: Vec<TrackedAttributeModifier>,
}

#[derive(Clone, Debug)]
pub(crate) struct TrackedAttributeModifier {
    uuid: Uuid,
    amount: f64,
    operation: u8,
}

impl TrackedEntityProperty {
    /// Converts to an [`AttributeProperty`]s.
    fn to_property(&self) -> AttributeProperty<'static> {
        AttributeProperty {
            key: Ident::new(self.key.clone()).unwrap(),
            value: self.value,
            modifiers: self
                .modifiers
                .iter()
                .map(|modifier| AttributeModifier {
                    uuid: modifier.uuid,
                    amount: modifier.amount,
                    operation: modifier.operation,
                })
                .collect(),
        }
    }
}

impl TrackedEntityAttributes {
    /// Creates a new instance of [`TrackedEntityAttributes`].
    pub fn new() -> Self {
        Self {
            modified: IndexMap::new(),
        }
    }

    /// Marks an attribute as modified.
    pub fn mark_modified(&mut self, attributes: &EntityAttributes, attribute: EntityAttribute) {
        if let Some(instance) = attributes.get(attribute) {
            self.modified.insert(attribute, instance.to_property());
        }
    }

    /// Returns the properties turned into a [`Vec`] of [`AttributeProperty`]s.
    pub fn get_properties(&self) -> Vec<AttributeProperty<'static>> {
        self.modified
            .iter()
            .map(|(_, property)| property.to_property())
            .collect()
    }

    /// Clears the modified attributes.
    pub fn clear(&mut self) {
        self.modified.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_compute_value() {
        let add_uuid = Uuid::new_v4();
        let mut attributes = EntityAttributes::new();
        attributes.set_base_value(EntityAttribute::GenericMaxHealth, 20.0);
        attributes.set_add_modifier(EntityAttribute::GenericMaxHealth, add_uuid, 10.0);
        attributes.set_multiply_base_modifier(
            EntityAttribute::GenericMaxHealth,
            Uuid::new_v4(),
            0.2,
        );
        attributes.set_multiply_base_modifier(
            EntityAttribute::GenericMaxHealth,
            Uuid::new_v4(),
            0.2,
        );
        attributes.set_multiply_total_modifier(
            EntityAttribute::GenericMaxHealth,
            Uuid::new_v4(),
            0.5,
        );

        assert_eq!(
            attributes.get_compute_value(EntityAttribute::GenericMaxHealth),
            Some(63.0) // ((20 + 10) * (1 + 0.2 + 0.2)) * (1 + 0.5)
        );

        attributes.remove_modifier(EntityAttribute::GenericMaxHealth, add_uuid);

        assert_eq!(
            attributes.get_compute_value(EntityAttribute::GenericMaxHealth),
            Some(42.0) // ((20) * (1 + 0.2 + 0.2)) * (1 + 0.5)
        );
    }
}