1 /*
 2 
 3   Moon Fullness API
 4   Author: Max Cantor <max@maxcantor.net>
 5   Version: 1.0
 6   
 7   This is a simple library to assist with bot decisionmaking based on
 8   the current fullness and phase of the moon according to NASA.
 9   
10   Current Features:
11    - Adjustable fullness threshold
12    - Threshold callback interface
13   
14   Planned Features:
15    - Waxing vs. Waning Detection
16    - Auto download of yearly JSON data?
17   
18   Usage:
19     const Moon = require('./moon.js');
20     const moon = new Moon();
21     moon.CheckPhase(Date.now(), onFullChange);
22 
23     // Called by the Moon library whenever the threshold is crossed
24     async function onFullChange(is_full) { /* see below */ }
25 
26 */
27 
28 const entries = require('./mooninfo_2023.json'); // via https://svs.gsfc.nasa.gov/4955
29 const FULLNESS_THRESHOLD = 80.00;
30 
31 function Moon(){
32     let entry = this.GetInfo(Date.now());
33     this.is_full = entry.fullness > FULLNESS_THRESHOLD;
34 }
35 
36 // Check the current moon fullness for the given date.
37 Moon.prototype.CheckPhase = function(date, onFullChange) {
38     let entry = this.GetInfo(date);
39     this.SetFullness(entry.fullness, onFullChange);
40 }
41 
42 // Return the moon info for the given time.
43 Moon.prototype.GetInfo = function(requestedDate) {
44     let requestedEntry;
45 
46     entries.forEach(function(entry) {
47         let timestamp = Date.parse(entry.time);
48         // console.log(`Comparing ${new Date(timestamp)} with ${new Date(date)}`);
49         if (timestamp > requestedDate && !requestedEntry) {
50             requestedEntry = {
51                 date: timestamp,
52                 age: parseFloat(entry.age),
53                 fullness: parseFloat(entry.phase)
54             };
55         }
56     });
57 
58     return requestedEntry;
59 }
60 
61 // Trigger the callback if the threshold has been crossed.
62 Moon.prototype.SetFullness = function(fullness, onFullChange) {
63     if ((fullness >= FULLNESS_THRESHOLD) && !this.is_full) {
64         this.is_full = true;
65         onFullChange(true);
66     } else if ((fullness < FULLNESS_THRESHOLD) && this.is_full) {
67         this.is_full = false;
68         onFullChange(false);
69     }
70 }
71 
72 module.exports = Moon;