-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathEventProvider.swift
213 lines (185 loc) · 9.73 KB
/
EventProvider.swift
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
//
// EventProvider.swift
// FOSSAsia
//
// Created by Pratik Todi on 27/02/16.
// Copyright © 2016 FossAsia. All rights reserved.
//
import Foundation
import SwiftyJSON
typealias CommitmentCompletionHandler = (Error?) -> Void
typealias EventsLoadingCompletionHandler = ([Event]?, Error?) -> Void
struct EventProvider {
fileprivate let dateFormatString = "yyyy-MM-dd'T'HH:mm:ssZ"
func getEvents(_ date: Date?, trackIds: [Int]?, completionHandler: @escaping EventsLoadingCompletionHandler) {
if !SettingsManager.isKeyPresentInUserDefaults(SettingsManager.keyForEvent) {
FetchDataService().fetchData(EventInfo.Events) { (_, error) -> Void in
guard error == nil else {
let error = Error(errorCode: .networkRequestFailed)
completionHandler(nil, error)
return
}
SettingsManager.saveKeyInUserDefaults(SettingsManager.keyForEvent, bool: true)
self.getEventsFromDisk(date, trackIds: trackIds, eventsLoadingCompletionHandler: { (events, error) -> Void in
guard let unwrappedEvents = events else {
let error = Error(errorCode: .jsonSystemReadingFailed)
completionHandler(nil, error)
return
}
completionHandler(unwrappedEvents, nil)
})
}
} else {
self.getEventsFromDisk(date, trackIds: trackIds, eventsLoadingCompletionHandler: { (events, error) -> Void in
guard let unwrappedEvents = events else {
let error = Error(errorCode: .jsonSystemReadingFailed)
completionHandler(nil, error)
return
}
completionHandler(unwrappedEvents, nil)
})
}
}
fileprivate func getEventsFromDisk(_ date: Date?, trackIds: [Int]?, eventsLoadingCompletionHandler: EventsLoadingCompletionHandler) {
if let dir: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first as NSString? {
do {
let filePath = dir.appendingPathComponent(SettingsManager.getLocalFileName(EventInfo.Events))
let eventsData = try Data(contentsOf: URL(fileURLWithPath: filePath), options: .mappedIfSafe)
let jsonObj = try JSON(data: eventsData)
guard let sessionsArray = jsonObj[EventInfo.Events.rawValue].array else {
let error = Error(errorCode: .jsonParsingFailed)
eventsLoadingCompletionHandler(nil, error)
return
}
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
getFavoriteEventsId({ (favoriteIds, error) -> Void in
guard let idArray = favoriteIds else {
eventsLoadingCompletionHandler(nil, error)
return
}
var sessions: [Event] = []
guard error == nil else {
eventsLoadingCompletionHandler(nil, error)
return
}
for session in sessionsArray {
guard let trackId = session[Constants.Sessions.track][Constants.Sessions.id].int,
let sessionId = session[Constants.Sessions.sessionId].string,
let sessionTitle = session[Constants.Sessions.title].string,
let sessionDescription = session[Constants.Sessions.description].string,
let sessionLocation = session[Constants.Sessions.location].string,
let sessionSpeakers = session[Constants.Sessions.speakers].array,
let sessionStartDateTime = session[Constants.Sessions.startTime].string,
let sessionEndDateTime = session[Constants.Sessions.endTime].string else {
continue
}
var sessionSpeakersNames: [Speaker] = []
for speaker in sessionSpeakers {
guard let speakerName = speaker[Constants.Sessions.speakerName].string else { continue }
let name = speakerName
sessionSpeakersNames.append(Speaker(name: name))
}
let tempSession = Event(id: sessionId,
trackCode: Event.Track(rawValue: trackId)!,
title: sessionTitle,
shortDescription: sessionDescription,
speakers: sessionSpeakersNames,
location: sessionLocation,
startDateTime: dateFormatter.date(from: sessionStartDateTime)!,
endDateTime: dateFormatter.date(from: sessionEndDateTime)!,
favorite: idArray.contains(sessionId))
sessions.append(tempSession)
}
if let filterTrackIds = trackIds {
sessions = sessions.filter({ filterTrackIds.contains($0.trackCode.rawValue) })
}
if let filterDate = date {
sessions = sessions.filter({ self.isSameDays(filterDate, $0.startDateTime as Date) })
sessions = sessions.sorted(by: { $0.startDateTime.compare($1.startDateTime as Date) == .orderedAscending })
}
eventsLoadingCompletionHandler(sessions, nil)
})
} catch {
eventsLoadingCompletionHandler(nil, Error(errorCode: .jsonSystemReadingFailed))
}
}
}
fileprivate func getFavoriteEventsId(_ completionHandler: ([String]?, Error?) -> Void) {
if let dir: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first as NSString? {
let filePath = dir.appendingPathComponent(SettingsManager.favouritesLocalFileName)
guard FileManager.default.fileExists(atPath: filePath) else {
let tempArray: JSON = []
if let data = tempArray.description.data(using: String.Encoding.utf8) {
do {
try data.write(to: URL(fileURLWithPath: filePath), options: .atomic)
} catch {
print(error)
}
}
completionHandler([], nil)
return
}
do {
let favoritesData = try Data(contentsOf: URL(fileURLWithPath: filePath), options: .mappedIfSafe)
let jsonObj = try JSON(data: favoritesData)
guard let favoritesArray = jsonObj.array else {
let error = Error(errorCode: .jsonParsingFailed)
completionHandler(nil, error)
return
}
completionHandler(favoritesArray.map { return $0.string! }, nil)
} catch {
completionHandler(nil, Error(errorCode: .jsonSystemReadingFailed))
}
}
}
func toggleFavorite(_ sessionId: String, completionHandler: CommitmentCompletionHandler) {
if let dir: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true).first as NSString? {
let filePath = dir.appendingPathComponent(SettingsManager.favouritesLocalFileName)
guard FileManager.default.fileExists(atPath: filePath) else {
let tempArray: JSON = [sessionId]
if let data = tempArray.description.data(using: String.Encoding.utf8) {
do {
try data.write(to: URL(fileURLWithPath: filePath), options: .atomic)
} catch {
print(error)
}
}
completionHandler(nil)
return
}
getFavoriteEventsId({ (favoriteIds, error) -> Void in
if var favoriteIdArray = favoriteIds {
if favoriteIdArray.contains(sessionId) {
favoriteIdArray = favoriteIdArray.filter({$0 != sessionId})
} else {
favoriteIdArray.append(sessionId)
}
if let data = JSON(favoriteIdArray).description.data(using: String.Encoding.utf8) {
do {
try data.write(to: URL(fileURLWithPath: filePath), options: .atomic)
} catch {
print(error)
}
completionHandler(nil)
}
} else {
completionHandler(error)
}
})
} else {
let error = Error(errorCode: .jsonSystemReadingFailed)
completionHandler(error)
}
}
fileprivate func isSameDays(_ date1: Date, _ date2: Date) -> Bool {
let calendar = Calendar.current
let comps1 = (calendar as NSCalendar).components([NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.day], from: date1)
let comps2 = (calendar as NSCalendar).components([NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.day], from: date2)
return (comps1.day == comps2.day) && (comps1.month == comps2.month) && (comps1.year == comps2.year)
}
}