- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseHelper.m
More file actions
Latest commit
238 lines (192 loc) · 9.72 KB
/
Copy pathDatabaseHelper.m
File metadata and controls
238 lines (192 loc) · 9.72 KB
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
//
// Database.m
// Timer
//
// Created by Chris Monahan on 4/30/14.
// Copyright 2014 Core Coding. All rights reserved.
//
#import"DatabaseHelper.h"
@implementationDatabaseHelper
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
#pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext {
if (__managedObjectContext != nil) {
return __managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [selfpersistentStoreCoordinator];
if (coordinator != nil) {
__managedObjectContext = [[NSManagedObjectContextalloc] init];
[__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel {
if (__managedObjectModel != nil) {
return __managedObjectModel;
}
NSURL *modelURL = [[NSBundlemainBundle] URLForResource:@"Database"withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModelalloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (__persistentStoreCoordinator != nil) {
return __persistentStoreCoordinator;
}
NSURL *storeURL = [[selfapplicationSupportDirectory] URLByAppendingPathComponent:@"Timer.sqlite"];
NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:[selfmanagedObjectModel]];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURL options:nilerror:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return __persistentStoreCoordinator;
}
#pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationSupportDirectory {
return [[[NSFileManagerdefaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] lastObject];
}
- (void)saveContext {
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
- (void)eraseAllContent {
NSURL *storeURL = [[selfapplicationSupportDirectory] URLByAppendingPathComponent:@"Timer.sqlite"];
// If you encounter schema incompatibility errors during development, you can reduce their frequency by: Simply deleting the existing store:
[[NSFileManagerdefaultManager] removeItemAtURL:storeURL error:nil];
}
- (NSArray *)grabAllEntries {
// Test listing all FailedBankInfos from the store
NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];
NSManagedObjectContext *context = [selfmanagedObjectContext];
NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Timesheet"inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
return [context executeFetchRequest:fetchRequest error:&error];
}
- (NSManagedObjectID *)addEntryWithDate:(NSDate *)datewithTitle:(NSString *)titlewithClient:(NSString *)client {
NSManagedObjectContext *context = [selfmanagedObjectContext];
Timesheet *timesheet = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Timesheet"inManagedObjectContext:context];
timesheet.start = date;
timesheet.title = title;
timesheet.client = client;
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
return [timesheet objectID];
}
- (void)addNote:(NSString *)activityToTimesheet:(NSManagedObjectID *)object {
NSManagedObjectContext *context = [selfmanagedObjectContext];
Note *note = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Note"inManagedObjectContext:context];
[note setActivity:activity];
Timesheet *timesheet = [selfgetEntryFromObject:object];
[timesheet addNotesObject:note];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
- (Timesheet *)getEntryFromObject:(NSManagedObjectID *)object {
// Test listing all FailedBankInfos from the store
NSManagedObjectContext *context = [selfmanagedObjectContext];
NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Timesheet"inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];
[fetchRequest setEntity:entity];
NSError *error;
Timesheet *sheet = (Timesheet *)[context existingObjectWithID:object error:&error];
[sheet setEnd:[NSDatedate]];
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
return sheet;
}
- (unsignedint)getDurationFromCompletedTasksWithCurrentTasks:(NSArray *)databaseObjects {
unsignedint duration = 0;
long lastStart = 0;
long lastEnd = 0;
// calculate day of year for today's date
NSCalendar *gregorian = [[NSCalendaralloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnitinUnit:NSYearCalendarUnitforDate:[NSDatedate]];
// loop over previous tasks and add to the overall duration
NSManagedObjectContext *context = [selfmanagedObjectContext];
NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Timesheet"inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (Timesheet *sheet in fetchedObjects) {
// now that we have valid dates we can calculate the day of year
NSUInteger sheetDayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnitinUnit:NSYearCalendarUnitforDate:sheet.start];
// is this entry from today?
if (dayOfYear == sheetDayOfYear) {
// calculate start and end times in unix time
long start = [sheet.start timeIntervalSince1970];
long end = [sheet.end timeIntervalSince1970];
// if this database object is still selected - use current date as end date regardless if it's null or has a date
if ([databaseObjects containsObject:[sheet objectID]]) {
//NSLog(@"found invalid sheet, start %@, end %@ - using current time for end - TODO - need to make sure task is active!", sheet.start, sheet.end);
end = [[NSDatedate] timeIntervalSince1970];
}
// this timestamp entry may still be open
if (end == 0) {
NSLog(@"found invalid sheet, start %@, end %@ - using current time for end", sheet.start, sheet.end);
// end = [[NSDate date] timeIntervalSince1970];
}
// make sure we have a valid task start date and end date
if (end < start) {
NSLog(@"found invalid sheet, start %@, end %@", sheet.start, sheet.end);
continue;
}
if (!lastStart && !lastEnd) {
// we don't have entries yet, save current values
lastStart = start;
lastEnd = end;
} elseif (start >= lastStart && start <= lastEnd && end >= lastEnd) {
// start date falls in the middle of the previous range, extend end time to new end time
lastEnd = end;
} elseif (end >= lastStart && end <= lastEnd && start <= lastStart) {
// end date falls in the middle of the previous range, use new start time
lastStart = start;
} elseif (start <= lastStart && end >= lastEnd) {
// start and end date extend beyond previous range, extend both
lastStart = start;
lastEnd = end;
} elseif (start >= lastStart && end <= lastEnd) {
// start and end date fall in between previous range, don't do anything
} else {
duration += (long) lastEnd - (long) lastStart;
lastStart = start;
lastEnd = end;
}
}
}
// make sure we capture the last value from the loop
duration += (long) lastEnd - (long) lastStart;
return duration;
}
- (void)updateSheet:(Timesheet *)sheetwithEndDate:(NSDate *)theDate {
[sheet setEnd:theDate];
NSError *error;
NSManagedObjectContext *context = [selfmanagedObjectContext];
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
@end