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
// Copyright (c) 2020 iliana destroyer of worlds <iliana@buttslol.net>
// SPDX-License-Identifier: CC-BY-NC-4.0
//
// This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International
// License. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc/4.0/
// or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.

use crate::calendar::{lunar_phase, lunar_phase_at_or_after, lunar_phase_at_or_before};
use crate::conv::{chrono_from_fixed, fixed_from_chrono};
use crate::phase::PrincipalPhase;
use chrono::{Date, DateTime, Duration, Utc};
use core::iter::FusedIterator;
use core::ops::{Bound, RangeBounds};

fn min_time() -> DateTime<Utc> {
    chrono::MIN_DATE.and_hms(0, 0, 0)
}

fn max_time() -> DateTime<Utc> {
    chrono::MAX_DATE.and_hms_nano(23, 59, 59, 999_999_999)
}

fn add_day(t: DateTime<Utc>, positive: bool) -> DateTime<Utc> {
    t.checked_add_signed(Duration::days(if positive { 1 } else { -1 })).unwrap_or_else(|| {
        if positive {
            max_time()
        } else {
            min_time()
        }
    })
}

fn handle_bound<T: Copy, F>(bound: Bound<&T>, default: F) -> (T, bool)
where
    F: Fn() -> T,
{
    match bound {
        Bound::Included(t) => (*t, false),
        Bound::Excluded(t) => (*t, true),
        Bound::Unbounded => (default(), false),
    }
}

/// Returns an iterator of principal phases and their moments.
///
/// ```
/// use chrono::{TimeZone, Utc};
/// use esbat::PrincipalPhase;
///
/// let start = Utc.ymd(2020, 10, 1).and_hms(0, 0, 0);
/// let end = Utc.ymd(2020, 11, 1).and_hms(0, 0, 0);
/// let mut iter = esbat::lunar_phase_iter(start..end);
///
/// assert_eq!(iter.next().unwrap().0, PrincipalPhase::FullMoon);
/// assert_eq!(iter.next().unwrap().0, PrincipalPhase::LastQuarter);
/// assert_eq!(iter.next().unwrap().0, PrincipalPhase::NewMoon);
/// assert_eq!(iter.next().unwrap().0, PrincipalPhase::FirstQuarter);
/// assert_eq!(iter.next().unwrap().0, PrincipalPhase::FullMoon);
/// assert!(iter.next().is_none());
/// ```
pub fn lunar_phase_iter<B>(range: B) -> Iter
where
    B: RangeBounds<DateTime<Utc>>,
{
    let (start, start_excl) = handle_bound(range.start_bound(), min_time);
    let (end, end_excl) = handle_bound(range.end_bound(), max_time);
    Iter::new(start, start_excl, end, end_excl)
}

/// Principal phase iterator.
///
/// This struct is created by [`lunar_phase_iter`].
#[derive(Debug, Clone)]
pub struct Iter {
    bound: Option<(DateTime<Utc>, DateTime<Utc>)>,
    positive: bool,
}

impl Iter {
    fn new(
        mut start: DateTime<Utc>,
        start_excl: bool,
        mut end: DateTime<Utc>,
        end_excl: bool,
    ) -> Iter {
        fn close_to_phase(t: DateTime<Utc>) -> bool {
            let x = lunar_phase(fixed_from_chrono(t)).rem_euclid(90.0);
            x < 0.00001 || 89.99999 < x
        }

        let positive = start <= end;
        if start_excl && close_to_phase(start) {
            start = add_day(start, positive);
        }
        if end_excl && close_to_phase(end) {
            end = add_day(end, !positive);
        }
        Iter { bound: Some((start, end)), positive }
    }
}

impl Iterator for Iter {
    type Item = (PrincipalPhase, DateTime<Utc>);

    fn next(&mut self) -> Option<(PrincipalPhase, DateTime<Utc>)> {
        let (start, end) = self.bound?;
        let start = fixed_from_chrono(start);

        let phase = lunar_phase(start);
        let phase = if self.positive {
            if phase <= 90.0 {
                PrincipalPhase::FirstQuarter
            } else if phase <= 180.0 {
                PrincipalPhase::FullMoon
            } else if phase <= 270.0 {
                PrincipalPhase::LastQuarter
            } else {
                PrincipalPhase::NewMoon
            }
        } else if phase >= 270.0 {
            PrincipalPhase::LastQuarter
        } else if phase >= 180.0 {
            PrincipalPhase::FullMoon
        } else if phase >= 90.0 {
            PrincipalPhase::FirstQuarter
        } else {
            PrincipalPhase::NewMoon
        };

        let next_rd = if self.positive {
            lunar_phase_at_or_after(phase.as_angle(), start)
        } else {
            lunar_phase_at_or_before(phase.as_angle(), start)
        };

        if let Some(next) = chrono_from_fixed(next_rd) {
            if self.positive && next <= end {
                self.bound = Some((add_day(next, true), end));
                return Some((phase, next));
            } else if !self.positive && next >= end {
                self.bound = Some((add_day(next, false), end));
                return Some((phase, next));
            }
        }

        self.bound = None;
        None
    }
}

impl FusedIterator for Iter {}

#[cfg(test)]
#[test]
fn test_iter_rev() {
    use chrono::TimeZone;

    let start = Utc.ymd(2020, 11, 1).and_hms(0, 0, 0);
    let end = Utc.ymd(2020, 10, 1).and_hms(0, 0, 0);
    let mut iter = lunar_phase_iter(start..end);

    assert_eq!(iter.next().unwrap().0, PrincipalPhase::FullMoon);
    assert_eq!(iter.next().unwrap().0, PrincipalPhase::FirstQuarter);
    assert_eq!(iter.next().unwrap().0, PrincipalPhase::NewMoon);
    assert_eq!(iter.next().unwrap().0, PrincipalPhase::LastQuarter);
    assert_eq!(iter.next().unwrap().0, PrincipalPhase::FullMoon);
    assert!(iter.next().is_none());
}

/// Returns an iterator of principal phases and the days they fall on.
///
/// ```
/// use chrono::{TimeZone, Utc};
/// use esbat::PrincipalPhase;
///
/// let start = Utc.ymd(2020, 10, 1);
/// let end = Utc.ymd(2020, 11, 1);
/// let mut iter = esbat::daily_lunar_phase_iter(start..end);
///
/// assert_eq!(iter.next().unwrap(), (PrincipalPhase::FullMoon, Utc.ymd(2020, 10, 1)));
/// assert_eq!(iter.next().unwrap(), (PrincipalPhase::LastQuarter, Utc.ymd(2020, 10, 10)));
/// assert_eq!(iter.next().unwrap(), (PrincipalPhase::NewMoon, Utc.ymd(2020, 10, 16)));
/// assert_eq!(iter.next().unwrap(), (PrincipalPhase::FirstQuarter, Utc.ymd(2020, 10, 23)));
/// assert_eq!(iter.next().unwrap(), (PrincipalPhase::FullMoon, Utc.ymd(2020, 10, 31)));
/// assert!(iter.next().is_none());
/// ```
pub fn daily_lunar_phase_iter<B>(range: B) -> DailyIter
where
    B: RangeBounds<Date<Utc>>,
{
    fn fix(t: Date<Utc>, down: bool) -> DateTime<Utc> {
        if down {
            t.and_hms(0, 0, 0)
        } else {
            t.and_hms_nano(23, 59, 59, 999_999_999)
        }
    }

    let (start, start_excl) = handle_bound(range.start_bound(), || chrono::MIN_DATE);
    let (end, end_excl) = handle_bound(range.end_bound(), || chrono::MAX_DATE);
    let positive = start <= end;
    DailyIter { inner: Iter::new(fix(start, positive), start_excl, fix(end, !positive), end_excl) }
}

/// Principal phase iterator by day.
///
/// This struct is created by [`daily_lunar_phase_iter`].
#[derive(Debug, Clone)]
pub struct DailyIter {
    inner: Iter,
}

impl Iterator for DailyIter {
    type Item = (PrincipalPhase, Date<Utc>);

    fn next(&mut self) -> Option<(PrincipalPhase, Date<Utc>)> {
        let next = self.inner.next()?;
        dbg!(&self.inner);
        Some((next.0, next.1.date()))
    }
}

impl FusedIterator for DailyIter {}

#[cfg(test)]
#[test]
fn test_daily_iter_rev() {
    use chrono::TimeZone;

    let start = Utc.ymd(2020, 11, 1);
    let end = Utc.ymd(2020, 10, 1);
    let mut iter = daily_lunar_phase_iter(start..end);

    assert_eq!(iter.next().unwrap(), (PrincipalPhase::FullMoon, Utc.ymd(2020, 10, 31)));
    assert_eq!(iter.next().unwrap(), (PrincipalPhase::FirstQuarter, Utc.ymd(2020, 10, 23)));
    assert_eq!(iter.next().unwrap(), (PrincipalPhase::NewMoon, Utc.ymd(2020, 10, 16)));
    assert_eq!(iter.next().unwrap(), (PrincipalPhase::LastQuarter, Utc.ymd(2020, 10, 10)));
    assert_eq!(iter.next().unwrap(), (PrincipalPhase::FullMoon, Utc.ymd(2020, 10, 1)));
    assert!(iter.next().is_none());
}

#[cfg(test)]
#[test]
fn test_ranges() {
    use chrono::TimeZone;

    let start = Utc.ymd(2020, 10, 1).and_hms(0, 0, 0);
    let end = Utc.ymd(2020, 11, 1).and_hms(0, 0, 0);
    lunar_phase_iter(..);
    lunar_phase_iter(start..);
    lunar_phase_iter(..end);
    lunar_phase_iter(..=end);
    lunar_phase_iter(start..end);
    lunar_phase_iter(start..=end);

    let start = Utc.ymd(2020, 10, 1);
    let end = Utc.ymd(2020, 11, 1);
    daily_lunar_phase_iter(..);
    daily_lunar_phase_iter(start..);
    daily_lunar_phase_iter(..end);
    daily_lunar_phase_iter(..=end);
    daily_lunar_phase_iter(start..end);
    daily_lunar_phase_iter(start..=end);
}