chore(release): 0.2.3
[risinglegends.git] / src / shared / time.ts
1 export type TimeDay = 'morning' | 'afternoon';
2 export type TimeNight = 'evening' | 'night';
3 export type TimePeriod = TimeDay | TimeNight | 'any';
4
5 export class TimeManager {
6   dayLengthAsMS: number;
7   scaleFactor: number;
8
9   /**
10    * @param dayLength the number of minutes a day lasts
11    */
12   constructor(public dayLength: number = 120) {
13     this.scaleFactor = 30;  // this is because we only have 30 gradients
14     this.dayLengthAsMS = dayLength * 60 * 1000;
15   }
16
17   dayScaleFactor(): number {
18     return this.dayLength / 30;
19   }
20
21   getTimePeriod(): TimePeriod {
22     if(this.isMorning()) {
23       return 'morning';
24     }
25     else if(this.isAfternoon()) {
26       return 'afternoon';
27     }
28     else if(this.isEvening()) {
29       return 'evening';
30     }
31     else if(this.isNight()) {
32       return 'night';
33     }
34   }
35
36   getAmPm(): string {
37     if(this.get24Hour() < 12) {
38       return 'am';
39     }
40     else {
41       return 'pm';
42     }
43   }
44
45   get24Hour(): number {
46     // ensure that we use the right minutes w/ the hour
47     const date = new Date();
48     const mins = date.getMinutes();
49     const hours = date.getHours();
50     const minOffset = (hours % 2) * (this.dayLength/2);
51
52     const ratio = (mins + minOffset) / this.dayLength;
53
54     // hours in Day
55     const hour = Math.floor(ratio * 24);
56     return hour;
57   }
58
59   getHour(): number {
60     const ratio = (new Date()).getMinutes() / this.dayLength;
61
62     // hours in Day
63     const hour = Math.floor(ratio * 24);
64     return hour > 12 ? hour - 12 : hour;
65   }
66
67   gradientName(): string {
68     // we have to scale the current date over the day/scale factor for the right 
69     // background
70     const num =  Math.floor((new Date()).getMinutes() / this.dayScaleFactor());
71     return `sky-gradient-${num < 10 ? '0': ''}${num}`;
72   }
73
74   isNight(): boolean {
75     const min = this.get24Hour();
76     return (
77       min >= 0 && min < 5 ||
78         min >= 22 && min < 24
79     );
80   }
81
82   isMorning(): boolean {
83     const min = this.get24Hour();
84     return min >= 5 && min < 12;
85   }
86
87   isAfternoon(): boolean {
88     const min = this.get24Hour();
89     return min >= 12 && min < 18;
90   }
91
92   isEvening(): boolean {
93     const min = this.get24Hour();
94     return min >= 18 && min < 21;
95   }
96 }