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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Series represents a single column within a dataframe and wraps many `Array` like
//! functionality.
//! 
//! For methods implemented for a [`Series`], please check out the trait [`SeriesTrait`]
//! 
//! ## Example use:
//! 
//! ```
//! use blackjack::prelude::*;
//! 
//! let mut series = Series::arange(0, 5);
//! 
//! // Index and change elements
//! series[0] = 1;
//! series[1] = 0;
//!
//! assert_eq!(series[0], 1);
//! assert_eq!(series.sum(), 10);
//! assert_eq!(series.len(), 5);
//! ```

use std::ops::{Range, Index, IndexMut};
use std::iter::{FromIterator, Sum};
use std::convert::From;
use std::fmt;
use std::str::FromStr;

use num::*;
use stats;

pub mod overloaders;
use prelude::*;


/// Series struct for containing underlying Array and other meta data.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Series<T>
    where
        T: BlackJackData
{
    
    /// Name of the series, if added to a dataframe without a name, it will be assigned
    /// a default name equalling the cound of columns in the dataframe.
    pub name: Option<String>,

    /// The underlying values of the Series
    pub values: Vec<T>,

    dtype: DType
}

/// Constructor methods for `Series<T>`
impl<T> Series<T>
    where
        T: BlackJackData
{

    /// Create a new Series struct from an integer range with one step increments. 
    /// 
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series: Series<i32> = Series::arange(0, 10);
    /// ```
    pub fn arange(start: T, stop: T) -> Self
        where
            T: Integer + BlackJackData + ToPrimitive,
            Range<T>: Iterator, 
            Vec<T>: FromIterator<<Range<T> as Iterator>::Item>
    {
        let dtype = start.dtype();
        let values: Vec<T> = (start..stop).collect();
        Series { 
            name: None,
            dtype,
            values
        }
    }

    /// Convert the series into another [`DType`] (creates a new series)
    ///
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    ///
    /// let series: Series<i32> = Series::arange(0, 10);
    /// assert_eq!(series[0].dtype(), DType::I32);
    /// let new_series = series.astype::<f64>().unwrap();
    /// assert_eq!(new_series[0].dtype(), DType::F64);
    /// ```
    pub fn astype<A>(&self) -> Result<Series<A>, &'static str>
        where A: BlackJackData + FromStr
    {
        let values = self.values
                .clone()
                .into_iter()
                .map(|v| v.to_string())
                .map(|v| v.parse::<A>().map_err(|_| "Cannot cast into type"))
                .collect::<Result<Vec<A>, _>>()?;
        let series = Series {
            name: self.name.clone(),
            dtype: values[0].dtype(),
            values
        };
        Ok(series)
    }

    /// Convert this series into another [`DType`] (consumes current series)
    ///
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    ///
    /// let series: Series<i32> = Series::arange(0, 10);
    /// assert_eq!(series[0].dtype(), DType::I32);
    /// let new_series = series.into_type::<f64>().unwrap();
    /// assert_eq!(new_series[0].dtype(), DType::F64);
    /// ```
    pub fn into_type<A>(self) -> Result<Series<A>, &'static str>
        where A: BlackJackData + FromStr
    {
        let values = self.values
                .into_iter()
                .map(|v| v.to_string())
                .map(|v| v.parse::<A>().map_err(|_| "Cannot cast into type"))
                .collect::<Result<Vec<A>, _>>()?;
        let series = Series {
            name: self.name.clone(),
            dtype: values[0].dtype(),
            values
        };
        Ok(series)
    }

    /// Get a series of the unique elements held in this series
    /// 
    /// ## Example
    /// 
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series: Series<i32> = Series::from_vec(vec![1, 2, 1, 0, 1, 0, 1, 1]);
    /// let unique: Series<i32> = series.unique();
    /// assert_eq!(unique, Series::from_vec(vec![0, 1, 2]));
    /// ```
    pub fn unique(&self) -> Series<T>
        where T: PartialOrd + Copy
    {
        // Cannot use `HashSet` as f32 & f64 don't implement Hash
        let mut unique: Vec<T> = vec![];
        let mut values = self.values.clone();
        values.sort_by(|a, b| a.partial_cmp(b).unwrap());

        for val in values
        {
            if unique.len() > 0 {
                if val == unique[unique.len() - 1] {
                    continue
                } else {
                    unique.push(val)
                }
            } else {
                unique.push(val)
            }
        }
        
        Series::from_vec(unique)
        
    }

    /// Create a new Series struct from a vector, where T is supported by [`BlackJackData`]. 
    /// 
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series: Series<i32> = Series::from_vec(vec![1, 2, 3]);
    /// ```
    pub fn from_vec(vec: Vec<T>) -> Self
    {
        let dtype = vec[0].dtype();  // TODO: Do something better.
        Series { 
            name: None,
            dtype,
            values: vec
        }
    }

    /// Convert the series to a [`Vec`]  
    /// **Type Annotations required**
    /// Will coerce elements into the desired [`DType`] primitive, just as
    /// [`SeriesTrait::astype()`]. 
    /// 
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series = Series::from_vec(vec![1_f64, 2_f64, 3_f64]);
    /// 
    /// assert_eq!(
    ///     series.clone().into_vec(),
    ///     vec![1_f64, 2_f64, 3_f64]
    /// );
    /// ```
    pub fn into_vec(self) -> Vec<T> {
        self.values
    }

    /// Set the name of a series
    pub fn set_name(&mut self, name: &str) -> () {
        self.name = Some(name.to_string());
    }

    /// Get the name of the series; Series may not be assigned a string, 
    /// so an `Option` is returned.
    /// 
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let mut series = Series::from_vec(vec![1, 2, 3]);
    /// series.set_name("my-series");
    /// 
    /// assert_eq!(series.name(), Some("my-series".to_string()));
    /// ```
    pub fn name(&self) -> Option<String> {
        match self.name {
            Some(ref name) => Some(name.clone()),
            None => None
        }
    }

    /// Finds the returns a [`Series`] containing the mode(s) of the current
    /// [`Series`]
    pub fn mode(&self) -> Result<Self, &'static str>
        where T: BlackJackData + PartialOrd + Copy + ToPrimitive
    {
        if self.len() == 0 {
            return Err("Cannot compute mode of an empty series!")
        }

        let modes = stats::modes(self.values.iter().map(|v| *v));
        let modes = Series::from_vec(modes);
        Ok(modes)
    }

    /// Calculate the variance of the series  
    /// **NOTE** that whatever type is determined is what the values are cast to
    /// during calculation of the variance. 
    /// 
    /// ie. `series.var::<i32>()` will cast each element into `i32` as input
    /// for calculating the variance, and yield a `i32` value. If you want all
    /// values to be calculated as `f64` then specify that in the type annotation.
    pub fn var(&self) -> Result<f64, &'static str>
        where 
            T: BlackJackData + ToPrimitive + Copy
    {
        if self.len() == 0  {
            return Err("Cannot compute variance of an empty series!");
        }
        let var = stats::variance(self.values.iter().map(|v| *v));
        Ok(var)
    }

    /// Calculate the standard deviation of the series
    /// 
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series = Series::arange(0, 10).astype::<f32>().unwrap();
    /// 
    /// let std = series.std().unwrap(); // Ok(2.8722...)
    /// assert!(std > 2.87);
    /// assert!(std < 2.88);
    /// ```
    pub fn std(&self) -> Result<f64, &'static str>
        where T: BlackJackData + ToPrimitive + Copy
    {
        if self.len() == 0 {
            return Err("Cannot compute standard deviation of an empty series!")
        }
        let std = stats::stddev(self.values.iter().map(|v| *v));
        Ok(std)
    }

    /// Sum a given series, yielding the same type as the elements stored in the 
    /// series.
    pub fn sum(&self) -> T
        where
            T: Num + Copy + Sum
    {
        self.values
            .iter()
            .map(|v| *v)
            .sum()
    }

    /// Average / Mean of a given series - Requires specifying desired float 
    /// return annotation 
    /// 
    /// ## Example:
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series = Series::arange(0, 5);
    /// let mean = series.mean();
    /// 
    /// match mean {
    ///     Ok(result) => {
    ///         println!("Result is: {}", &result);
    ///         assert_eq!(result, 2.0);
    ///     },
    ///     Err(err) => {
    ///         panic!("Was unable to compute mean, error: {}", err);
    ///     }
    /// }
    /// ```
    pub fn mean<'a>(&'a self) -> Result<f64, &'static str>
        where
            T: ToPrimitive + Copy + Sum<&'a T> + Num + Sum
    {
        let total = self.sum().to_f64().unwrap();
        let count = self.len() as f64;
        Ok(total / count)
    }

    /// Calculate the quantile of the series
    /// 
    /// ## Example:
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series = Series::arange(0, 100).astype::<f32>().unwrap();
    /// let qtl = series.quantile(0.5).unwrap(); // `49.5_f32`
    /// 
    /// assert!(qtl < 49.51);
    /// assert!(qtl > 49.49);
    /// ```
    pub fn quantile(&self, quantile: f64) -> Result<f64, &'static str>
        where 
            T: ToPrimitive + BlackJackData
    {
        use rgsl::statistics::quantile_from_sorted_data;
        use std::cmp::Ordering;

        let mut vec = self
            .clone()
            .into_vec()
            .into_iter()
            .map(|v| v.to_f64().unwrap())
            .collect::<Vec<f64>>();

        vec.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
        let qtl = quantile_from_sorted_data(&vec[..], 1, vec.len(), quantile);
        Ok(qtl)
    }

    /// Calculate the median of a series
    pub fn median<'a>(&'a self) -> Result<f64, &'static str>
        where T: ToPrimitive + Copy + PartialOrd
    {
        if self.len() == 0 {
            return Err("Cannot calculate median of an empty series.")
        }
        let med_opt = stats::median(self.values.iter().map(|v| v.to_f64().unwrap()));
        match med_opt {
            Some(med) => Ok(med),
            None => Err(r#"Unable to calculate median, please create an issue!
                           as this wasn't expected to ever happen on a non-empty
                           series. :("#)
        }
    }

    /// Find the minimum of the series. If several elements are equally minimum,
    /// the first element is returned. If it's empty, an Error will be returned.
    /// 
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let series: Series<i32> = Series::arange(10, 100);
    /// 
    /// assert_eq!(series.min(), Ok(10));
    /// ```
    pub fn min(&self) -> Result<T, &'static str>
        where 
            T: Num + Clone + Ord + BlackJackData
    {
        let min = self.values.iter().min();
        match min {
            Some(m) => Ok(m.clone()),
            None => Err("Unable to find minimum of values, perhaps values is empty?")
        }
    }

    /// Exibits the same behavior and usage of [`SeriesTrait::min`], only
    /// yielding the [`Result`] of a maximum.
    pub fn max(&self) -> Result<T, &'static str>
        where 
            T: Num + Clone + Ord
    {
        let max = self.values.iter().max();
        match max {
            Some(m) => Ok(m.clone()),
            None => Err("Unable to find maximum of values, perhaps values is empty?")
        }
    }

    /// Determine the length of the Series
    pub fn len(&self) -> usize { self.values.len() }

    /// Determine if series is empty.
    pub fn is_empty(&self) -> bool { self.len() == 0 }

    /// Get the dtype, returns `None` if series dtype is unknown. 
    /// in such a case, calling `.astype()` to coerce all types to a single
    /// type is needed. 
    pub fn dtype(&self) -> DType {
        self.dtype.clone()
    }

    /// Append a [`BlackJackData`] element to the Series
    /// 
    /// ## Example
    /// ```
    /// use blackjack::prelude::*;
    /// 
    /// let mut series = Series::from_vec(vec![0, 1, 2]);
    /// assert_eq!(series.len(), 3);
    /// 
    /// series.append(3);
    /// assert_eq!(series.len(), 4);
    /// ```
    pub fn append<V: Into<T>>(&mut self, val: V) -> () {
        let v = val.into();
        self.values.push(v);
    }

    /// As boxed pointer, recoverable by `Box::from_raw(ptr)` or 
    /// `SeriesTrait::from_raw(*mut Self)`
    pub fn into_raw(self) -> *mut Self { 
        Box::into_raw(Box::new(self)) 
    }

    /// Create from raw pointer
    pub fn from_raw(ptr: *mut Self) -> Self { 
        unsafe { *Box::from_raw(ptr) } 
    }

    /// Group by method for grouping elements in a [`Series`]
    /// by key.
    ///
    /// ## Example
    ///
    /// ```
    /// use blackjack::prelude::*;
    ///
    /// let series = Series::from_vec(vec![1, 2, 3, 1, 2, 3]);
    /// let keys   = Series::from_vec(vec![4, 5, 6, 4, 5, 6]);
    ///
    /// let grouped: Series<i32> = series.groupby(keys).sum();
    /// assert_eq!(grouped.len(), 3);
    ///
    /// let mut vals = grouped.into_vec();
    /// vals.sort();
    /// assert_eq!(vals, vec![2, 4, 6]);
    /// ```
    pub fn groupby(&self, keys: Series<T>) -> SeriesGroupBy<T>
        where T: ToPrimitive
    {

        /* TODO: Revisit this to avoid the clones. Needs to keep the groups
           in order based on key order; match pandas. ie:

            >>> pd.Series([1, 2, 3, 1, 2, 3]).groupby([4, 5, 6, 4, 5, 6]).sum()
            4    2
            5    4
            6    6
            dtype: int64
        */
        use indexmap::IndexMap;

        let values = self.values.clone();

        let mut map: IndexMap<String, Vec<T>> = IndexMap::new();

        // Group values by their keys
        for (k, v) in keys.values.into_iter().zip(values.into_iter()) {
            let key = k.to_string();
            let mr = map.entry(key).or_insert(vec![]);
            mr.push(v);
        }

        // Create new series from the previous mapping.
        let groups = map
            .iter()
            .map(|(name, values)| {
                let mut series = Series::from_vec(values.clone());
                series.set_name(name.as_str());
                series
            })
            .collect();

        SeriesGroupBy::new(groups)
    }
}


// Support ref indexing
impl<T> Index<usize> for Series<T>
    where T: BlackJackData
{
    type Output = T;
    fn index(&self, idx: usize) -> &T {
        &self.values[idx]
    }
}

// Support ref mut indexing
impl<T: BlackJackData> IndexMut<usize> for Series<T> {
    fn index_mut(&mut self, idx: usize) -> &mut T {
        &mut self.values[idx]
    }
}

// Support Display for Series
impl<T> fmt::Display for Series<T>
    where
        T: BlackJackData,
        String: From<T>
{

    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

        use prettytable::{Table, Row, Cell};

        let mut table = Table::new();

        // Title (column name)
        table.add_row(
            Row::new(
                vec![
                    Cell::new(&self.name().unwrap_or("<NA>".to_string()))
                ]
            )
        );

        // Build remaining values.
        // TODO: Limit how many are actually printed.
        let _ = self.values
            .iter()
            .map(|v| {
                let v: String = v.clone().into();
                table.add_row(
                    Row::new(vec![
                        Cell::new(&format!("{}", v))
                    ])
                );
            })
            .collect::<Vec<()>>();

        write!(f, "{}\n", table)
    }
}