summaryrefslogtreecommitdiff
path: root/src/traits.rs
blob: b5785be1b57014fa0d1e39f198069b200e313017 (plain)
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
use chrono::{DateTime, Local, Utc};
use colored::Colorize;
use core::cmp::PartialEq;

pub trait IsStation {
  fn name(&self) -> &str;
  fn scheduled_arrival(&self) -> Option<&DateTime<Utc>>;
  fn real_arrival(&self) -> Option<&DateTime<Utc>>;
  fn ds100(&self) -> Option<&str>;

  fn to_fancy_string(&self) -> String {
    // travelynx used to send this entire precise date in case of an
    // unknown time instead of null. I'm not sure it still does this
    // (i have since seen it return null) but keeping this here just
    // in case
    let epoch = "1970-01-01T00:00:00Z".parse::<DateTime<Local>>().unwrap();

    let format_time = |time: &DateTime<Utc>| -> String {
        if time.eq(&epoch) {
          "??:??:?? ".to_owned()
        } else { // chrono's API for timezones is expressive, but reads like c++ …
          <DateTime<Local>>::from(*time).time().format("%T").to_string()
        }
    };

    format!(
      "{} {} – {} ({})",
      self
        .real_arrival()
        .map(format_time)
        .unwrap_or_else(||
          self.scheduled_arrival()
            .map(format_time).unwrap_or_else(|| "??:??:??".to_string())
        )
        .blue(),
      {
        let delay = match (self.real_arrival(), self.scheduled_arrival()) {
          (Some(a), Some(s)) => (a.time() - s.time()).num_minutes(),
          _ => 0
        };
        let text = format!("({:+})", delay);
        if delay > 0 {
          text.red()
        } else {
          text.green()
        }
      },
      self.ds100().unwrap_or("??").red(),
      self.name()
    )
  }
}