67 lines
2.4 KiB
Swift
67 lines
2.4 KiB
Swift
//
|
|
// PersistenceADD.swift
|
|
// Feels
|
|
//
|
|
// Created by Trey Tartt on 2/17/22.
|
|
//
|
|
|
|
import CoreData
|
|
|
|
extension PersistenceController {
|
|
public func add(mood: Mood, forDate date: Date, entryType: EntryType) {
|
|
if let existingEntry = getEntry(byDate: date) {
|
|
viewContext.delete(existingEntry)
|
|
try? viewContext.save()
|
|
}
|
|
|
|
let newItem = MoodEntry(context: viewContext)
|
|
newItem.timestamp = Date()
|
|
newItem.moodValue = Int16(mood.rawValue)
|
|
newItem.forDate = date
|
|
newItem.weekDay = Int16(Calendar.current.component(.weekday, from: date))
|
|
newItem.canEdit = true
|
|
newItem.canDelete = true
|
|
newItem.entryType = Int16(entryType.rawValue)
|
|
|
|
do {
|
|
try viewContext.save()
|
|
} catch {
|
|
let nsError = error as NSError
|
|
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
|
|
}
|
|
}
|
|
|
|
func fillInMissingDates() {
|
|
let endDate = ShowBasedOnVoteLogics.getLastDateVoteShouldExist()
|
|
|
|
let fetchRequest = NSFetchRequest<MoodEntry>(entityName: "MoodEntry")
|
|
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "forDate", ascending: false)]
|
|
let entries = try! viewContext.fetch(fetchRequest)
|
|
|
|
if let firstEntry = entries.last?.forDate {
|
|
let allDates: [Date] = Date.dates(from: firstEntry, to: endDate).map({
|
|
let zeroDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: $0)!
|
|
return zeroDate
|
|
})
|
|
|
|
let existingEntries: [Date] = entries.compactMap({
|
|
if let date = $0.forDate {
|
|
let zeroDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: date)!
|
|
return zeroDate
|
|
}
|
|
return nil
|
|
})
|
|
|
|
let allDatesSet = Set(allDates)
|
|
let existingEntriesSet = Set(existingEntries)
|
|
let missing = Array(allDatesSet.subtracting(existingEntriesSet)).sorted(by: >)
|
|
for date in missing {
|
|
// add 12 hours, if you enter a things right at 12:00.00 it wont show .... mabye
|
|
// due to utc offset?
|
|
let adjustedDate = Calendar.current.date(byAdding: .hour, value: 12, to: date)!
|
|
add(mood: .missing, forDate: adjustedDate, entryType: .filledInMissing)
|
|
}
|
|
}
|
|
}
|
|
}
|