chore(release): 0.2.7
[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 hour = this.get24Hour();
61     return hour > 12 ? hour - 12 : hour;
62   }
63
64   gradientName(): string {
65     // we have to scale the current date over the day/scale factor for the right 
66     // background
67     const num =  Math.floor((this.get24Hour()/24) * this.scaleFactor);
68     return `sky-gradient-${num < 10 ? '0': ''}${num}`;
69   }
70
71   isNight(): boolean {
72     const min = this.get24Hour();
73     return (
74       min >= 0 && min < 5 ||
75         min >= 21 && min < 24
76     );
77   }
78
79   isMorning(): boolean {
80     const min = this.get24Hour();
81     return min >= 5 && min < 12;
82   }
83
84   isAfternoon(): boolean {
85     const min = this.get24Hour();
86     return min >= 12 && min < 18;
87   }
88
89   isEvening(): boolean {
90     const min = this.get24Hour();
91     return min >= 18 && min < 21;
92   }
93 }