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
/*!
 * Amount
 */

use std::{
    fmt,
    ops::{Add, AddAssign, Div, Mul, SubAssign},
};

use rust_decimal::prelude::FromPrimitive;

use crate::pool::CommodityIndex;

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Amount {
    pub quantity: Decimal,
    pub commodity_index: Option<CommodityIndex>,
}

impl Amount {
    pub fn new(quantity: Decimal, commodity_index: Option<CommodityIndex>) -> Self {
        Self {
            quantity,
            commodity_index,
        }
    }

    /// Returns an absolute (positive) Amount.
    pub fn abs(&self) -> Amount {
        let mut result = self.clone();
        result.quantity.set_sign_positive();
        result
    }

    /// Creates a new Amount instance.
    /// Parses the quantity only and uses the given commodity index.
    pub fn parse(amount: &str, commodity_index: Option<CommodityIndex>) -> Option<Self> {
        if amount.is_empty() {
            return None;
        }

        let quantity_result = Decimal::from_str(amount);
        if quantity_result.is_err() {
            return None;
        }

        let amount = Self {
            quantity: quantity_result.unwrap(),
            commodity_index,
        };

        Some(amount)
    }

    pub fn copy_from(other: &Amount) -> Self {
        // let com = match &other.commodity {
        //     Some(other_commodity) => {
        //         //let symbol = &other.commodity.as_ref().unwrap().symbol;
        //         let s = &other_commodity.symbol;
        //         let c = Commodity::new(s);
        //         Some(c)
        //     }
        //     None => None,
        // };

        Self {
            quantity: other.quantity,
            commodity_index: other.commodity_index,
        }
    }

    pub fn null() -> Self {
        Self {
            quantity: 0.into(),
            commodity_index: None,
        }
    }

    pub fn add(&mut self, other: &Amount) {
        if self.commodity_index != other.commodity_index {
            log::error!("different commodities");
            panic!("don't know yet how to handle this")
        }
        if other.quantity.is_zero() {
            // nothing to do
            return;
        }

        self.quantity += other.quantity;
    }

    /// Creates an amount with the opposite sign on the quantity.
    pub fn inverse(&self) -> Amount {
        let new_quantity = if self.quantity.is_sign_positive() {
            let mut x = self.quantity.clone();
            x.set_sign_negative();
            x
        } else {
            self.quantity
        };

        Amount::new(new_quantity, self.commodity_index)
    }

    /// Inverts the sign on the amount.
    pub fn invert(&mut self) {
        if self.quantity.is_sign_positive() {
            self.quantity.set_sign_negative();
        } else {
            self.quantity.set_sign_positive();
        }
    }

    /// Indicates whether the amount is initialized.
    /// This is a 0 quantity and no Commodity.
    pub fn is_null(&self) -> bool {
        if self.quantity.is_zero() {
            return self.commodity_index.is_none();
        } else {
            false
        }
    }

    pub fn is_zero(&self) -> bool {
        self.quantity.is_zero()
    }
}

impl std::ops::Add<Amount> for Amount {
    type Output = Amount;

    fn add(self, rhs: Amount) -> Self::Output {
        if self.commodity_index != rhs.commodity_index {
            panic!("don't know yet how to handle this")
        }

        let sum = self.quantity + rhs.quantity;

        Amount::new(sum, self.commodity_index)
    }
}

impl AddAssign<Amount> for Amount {
    fn add_assign(&mut self, other: Amount) {
        if self.commodity_index != other.commodity_index {
            panic!("don't know yet how to handle this")
        }

        self.quantity += other.quantity;
    }
}

impl Div for Amount {
    type Output = Amount;

    fn div(self, rhs: Self) -> Self::Output {
        // if self.quantity.is_zero() || rhs.quantity.is_zero() {
        //     todo!("handle no quantity");
        // }

        let mut result = Amount::new(0.into(), None);

        if self.commodity_index.is_none() {
            result.commodity_index = rhs.commodity_index;
        } else {
            result.commodity_index = self.commodity_index
        }

        result.quantity = self.quantity / rhs.quantity;

        result
    }
}

impl Mul<Amount> for Amount {
    type Output = Amount;

    fn mul(self, other: Amount) -> Amount {
        let quantity = self.quantity * other.quantity;

        let commodity_index = if self.commodity_index.is_none() {
            other.commodity_index
        } else {
            self.commodity_index
        };

        Amount::new(quantity, commodity_index)
    }
}

impl From<i32> for Amount {
    fn from(value: i32) -> Self {
        Amount::new(Decimal::from(value), None)
    }
}

impl SubAssign<Amount> for Amount {
    fn sub_assign(&mut self, other: Amount) {
        if self.commodity_index != other.commodity_index {
            panic!("The commodities do not match");
        }

        self.quantity -= other.quantity;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Decimal(rust_decimal::Decimal);

const ZERO: Decimal = Decimal(rust_decimal::Decimal::ZERO);

impl Decimal {
    pub const ZERO: Decimal = ZERO;

    pub fn from_str(str: &str) -> Result<Self, anyhow::Error> {
        Ok(Self(rust_decimal::Decimal::from_str_exact(str)?))
    }

    pub fn is_sign_positive(&self) -> bool {
        self.0.is_sign_positive()
    }

    pub fn is_zero(&self) -> bool {
        self.0.is_zero()
    }

    pub fn set_sign_negative(&mut self) {
        self.0.set_sign_negative(true)
    }

    pub fn set_sign_positive(&mut self) {
        self.0.set_sign_positive(true)
    }
}

impl From<i32> for Decimal {
    fn from(value: i32) -> Self {
        Decimal(rust_decimal::Decimal::from(value))
    }
}

impl From<f32> for Decimal {
    fn from(value: f32) -> Self {
        Decimal(rust_decimal::Decimal::from_f32(value).unwrap())
    }
}

impl Add<Decimal> for Decimal {
    type Output = Decimal;

    fn add(self, other: Decimal) -> Decimal {
        Decimal(self.0 + other.0)
    }
}

impl AddAssign<Decimal> for Decimal {
    fn add_assign(&mut self, other: Decimal) {
        self.0 += other.0;
    }
}

impl Div<Decimal> for Decimal {
    type Output = Decimal;

    fn div(self, other: Decimal) -> Decimal {
        Self(self.0.div(other.0))
    }
}

impl Mul<Decimal> for Decimal {
    type Output = Decimal;

    fn mul(self, other: Decimal) -> Decimal {
        Self(self.0 * other.0)
    }
}

impl SubAssign<Decimal> for Decimal {
    fn sub_assign(&mut self, other: Decimal) {
        self.0 -= other.0;
    }
}

impl fmt::Display for Decimal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use rust_decimal::prelude::ToPrimitive;

    use super::{Amount, Decimal};

    #[test]
    fn test_decimal() {
        let x = Decimal::from(5);

        assert_eq!(Some(5), x.0.to_i32());
    }

    #[test]
    fn test_division() {
        let a = Amount::new(10.into(), Some(3.into()));
        let b = Amount::new(5.into(), Some(3.into()));
        let expected = Amount::new(2.into(), Some(3.into()));

        let c = a / b;

        assert_eq!(expected, c);
    }
}