aboutsummaryrefslogtreecommitdiff
path: root/readingplan.py
blob: 4386121cf5d600fc34fe4183a1c8825b87ccd46b (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
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
#
# The MIT License (MIT)
#
# Copyright (c) 2018 Daniel Moch
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import json
import os

DAYS_OF_WEEK = (
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    )

MONTHS = (
    ('January', 31,),
    ('February', 28,),
    ('March', 31,),
    ('April', 30,),
    ('May', 31,),
    ('June', 30,),
    ('July', 31,),
    ('August', 31,),
    ('September', 30,),
    ('October', 31,),
    ('November', 30,),
    ('December', 31,),
    )

class ReadingPlanError(Exception):
    """
    Exception thrown by the ReadingPlan class

    Attributes:
        message - The error message
    """
    message = None

    def __init__(self, message):
        super().__init__()
        self.message = message

class ReadingPlan:
    """
    Once initialized, maintain state of the plan so the schedule
    function can simply ask for the next day's reading.
    """
    _initialized = False
    _current_month = 0
    _current_day = 1
    _day_of_week = 0

    _sections = {}
    _days_sections = {}
    _days_sections_fallback = {}
    _reading_dictionaries = {}
    _reading_indices = {}
    done = False

    @staticmethod
    def _print_dbg(method, message):
        if 'READINGPLAN_DEBUG' in os.environ.keys():
            print('ReadingPlan.' + method + ': ' + message)

    def _general_init(self, config):
        jan1_day_of_week = config['general']['jan1_day_of_week']
        for idx, day in enumerate(DAYS_OF_WEEK):
            if day.upper() == jan1_day_of_week.upper():
                self._day_of_week = idx
                break

    def _days_sections_init(self, config, section):
        for day in DAYS_OF_WEEK:
            day_key = day.lower()
            if day_key in config[section].keys():
                self._days_sections[day] = config[section][day_key]
            else:
                self._print_dbg('_days_sections_init', 'No readings ' \
                        + 'planned for ' + day + 's')
                self._days_sections[day] = None

    def _days_sections_fallback_init(self, config, section):
        for day in DAYS_OF_WEEK:
            day_key = day.lower()
            if day_key in config[section].keys():
                self._days_sections_fallback[day] = \
                        config[section][day_key]
            else:
                self._print_dbg('_days_sections_fallback_init', 'No ' \
                        + 'fallback readings planned for ' + day + 's')
                self._days_sections_fallback[day] = None

    def _section_init(self, config, section):
        if 'name' in config[section].keys():
            self._sections[section] = config[section]['name']
        else:
            self._print_dbg('_section_init', 'No section name ' + \
                    'specified for ' + section)
            self._print_dbg('_section_init', 'Using ' + section + \
                    ' as name')
            self._sections[section] = section
        reading_dictionary = []
        try:
            with open('sections/' + section + '.json', 'r') as sfile:
                reading_dictionary = json.load(sfile)
                self._reading_dictionaries[section] = reading_dictionary
        except FileNotFoundError as error:
            raise ReadingPlanError(section + ' provided in ' + \
                    'configuration file, but ' + error.filename + \
                    ' does not exist')
        if 'book' in config[section].keys():
            book = config[section]['book']
            if 'chapter' in config[section].keys():
                chapter = config[section]['chapter']
            else:
                chapter = '1'
            for dictionary in reading_dictionary:
                if dictionary['book'] == book and \
                        dictionary['reading'] == chapter:
                    self._reading_indices[section] = \
                        dictionary['index']
        if section not in self._reading_indices.keys():
            self._reading_indices[section] = 0

    def _print_plan_info(self):
        message = 'Sections configured: '
        for section in self._sections.values():
            message += section + ', '
        message = message[0:-2]
        print(message)
        print('Jan. 1 configured to ' + DAYS_OF_WEEK[self._day_of_week])
        print('Configured daily readings:')
        for day in self._days_sections.keys():
            if self._days_sections[day] is None:
                print('\t' + day + ': No reading')
            else:
                message = '\t' + day + ': '
                for section in self._days_sections[day].split(','):
                    message += self._sections[section] + ', '
                message = message[0:-2]
                print(message)
        print('Configured fallback readings:')
        for day in self._days_sections_fallback.keys():
            if self._days_sections_fallback[day] is None:
                print('\t' + day + ': No reading')
            else:
                message = '\t' + day + ': '
                for section in self._days_sections_fallback[day].split(','):
                    message += self._sections[section] + ', '
                message = message[0:-2]
                print(message)

    def build_plan(self, config):
        for section in config.sections():
            if section == 'general':
                self._general_init(config)
            elif section == 'days_sections':
                self._days_sections_init(config, section)
            elif section == 'days_sections_fallback':
                self._days_sections_fallback_init(config, section)
            else:
                self._section_init(config, section)
        self._print_plan_info()
        self._initialized = True

    def _next_day(self):
        if self._current_day == MONTHS[self._current_month][1]:
            self._current_day = 1
            self._current_month += 1
            if self._current_month == len(MONTHS):
                self.done = True
        else:
            self._current_day += 1

        last_day = len(DAYS_OF_WEEK) - 1
        if self._day_of_week == last_day:
            self._day_of_week = 0
        else:
            self._day_of_week += 1

    def _readings(self, sections):
        readings = []
        if sections is not None:
            for section in sections.split(','):
                if section not in self._sections.keys():
                    raise ValueError(section + ' is not a known section')

                section_dict = self._reading_dictionaries[section]
                for reading_dict in section_dict:
                    if reading_dict['index'] == self._reading_indices[section]:
                        reading = {}
                        reading['section'] = self._sections[section]
                        reading['book'] = reading_dict['book']
                        reading['reading'] = reading_dict['reading']
                        readings.append(reading)
                        self._reading_indices[section] += 1
                        break
        return readings

    def next_reading(self):
        if not self._initialized:
            raise RuntimeError('Attempting to use an uninitialized ReadingPlan')
        results = {}
        readings = []
        today_sections = self._days_sections[DAYS_OF_WEEK[self._day_of_week]]
        today_sections_fallback = \
                self._days_sections_fallback[DAYS_OF_WEEK[self._day_of_week]]
        for reading in self._readings(today_sections):
            readings.append(reading)

        if readings == []:
            for reading in self._readings(today_sections_fallback):
                readings.append(reading)
        results = {
            'day_of_week': DAYS_OF_WEEK[self._day_of_week],
            'day': self._current_day,
            'month': MONTHS[self._current_month][0],
            'readings': readings
            }
        self._next_day()
        return results