<commit_before>//
//  SBAScheduledActivityManager.swift
//  BridgeAppSDK
//
//  Copyright © 2016 <NAME>. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1.  Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2.  Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3.  Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

import ResearchKit
import BridgeSDK

// TODO: syoung 04/14/2016 This is a WIP first draft of an implementation of schedule fetching that
// works for Lilly but is not complete for Parkinsons (which include a separate section for "keep going"
// activities *and* includes surveys that are build server-side (currently not supported by this implementation)


public enum SBAScheduledActivitySection {
    
    case None
    case ExpiredYesterday
    case Today
    case KeepGoing
    case Tomorrow
}

public protocol SBAScheduledActivityManagerDelegate: SBAAlertPresenter {
    func reloadTable(scheduledActivityManager: SBAScheduledActivityManager)
}

public class SBAScheduledActivityManager: NSObject, SBASharedInfoController, ORKTaskViewControllerDelegate {
    
    public weak var delegate: SBAScheduledActivityManagerDelegate?
    
    public var sections: [SBAScheduledActivitySection] = [.Today, .KeepGoing]
    public var activities: [SBBScheduledActivity] = []
    
    private var reloading: Bool = false
    public func reloadData() {
        
        // Exit early if already reloading activities. This can happen if the user flips quickly back and forth from
        // this tab to another tab.
        if (reloading) { return }
        reloading = true
        
        SBAUserBridgeManager.fetchChangesToScheduledActivities(activities, todayOnly: false) { [weak self] (obj, error) in
            guard (error == nil), let scheduledActivities = obj as? [SBBScheduledActivity] else { return }
            
            dispatch_async(dispatch_get_main_queue(), {
                self?.loadActivities(scheduledActivities)
                self?.reloading = false
            })
        }
    }
    
    public func loadActivities(scheduledActivities: [SBBScheduledActivity]) {
        
        // Filter out any sections that aren't shown
        let filters = sections.mapAndFilter({ filterPredicateForScheduledActivitySection($0) })
        let includedSections = NSCompoundPredicate(orPredicateWithSubpredicates: filters)
        
        // Filter the scheduled activities to only include those that *this* version of the app is designed
        // to be able to handle. Currently, that means only taskReference activities with an identifier that
        // maps to a known task.
        self.activities = scheduledActivities.filter({ (schedule) -> Bool in
            return taskReferenceForSchedule(schedule) != nil && includedSections.evaluateWithObject(schedule)
        })
        
        // reload table
        self.delegate?.reloadTable(self)
    }
    
    
    // MARK: Data Source Management
    
    public func numberOfSections() -> Int {
        return sections.count
    }
    
    public func numberOfRowsInSection(section: Int) -> Int {
        return scheduledActivitiesForSection(section).count
    }
    
    private func scheduledActivitySectionForTableSection(section: Int) -> SBAScheduledActivitySection {
        guard section < sections.count else { return .None }
        return sections[section]
    }
    
    private func scheduledActivitiesForSection(section: Int) ->[SBBScheduledActivity] {
        let scheduledActivitySection = scheduledActivitySectionForTableSection(section)
        guard let predicate = filterPredicateForScheduledActivitySection(scheduledActivitySection) else { return [] }
        return activities.filter({ predicate.evaluateWithObject($0) })
    }
    
    public func sectionTitle(section: Int) -> String? {
        
        // Always return nil for the first section and if there are no rows in the section
        guard section > 0 && scheduledActivitiesForSection(section).count > 0
        else {
            return nil
        }
        
        // Return default localized string for each section
        switch scheduledActivitySectionForTableSection(section) {
        case .ExpiredYesterday:
            return Localization.localizedString("SBA_ACTIVITY_YESTERDAY")
        case .Today:
            return Localization.localizedString("SBA_ACTIVITY_TODAY")
        case .KeepGoing:
            return Localization.localizedString("SBA_ACTIVITY_KEEP_GOING")
        case .Tomorrow:
            return Localization.localizedString("SBA_ACTIVITY_TOMORROW")
        default:
            return nil
        }
    }
    
    public func filterPredicateForScheduledActivitySection(section: SBAScheduledActivitySection) -> NSPredicate? {
        
        // syoung 05/06/2016 As of Swift 2.2, there is no equivilent to NSStringFromSelector
        let expiredKey = "expiresOn"
        let scheduledKey = "scheduledOn"
        let finishedKey = "finishedOn"
        let optionalKey = "persistent"
        
        // For unscheduled we need to also filter out those tasks that were finished prior to today
        let finishedToday = NSPredicate(day: NSDate(), dateKey: finishedKey)
        let unfinished = NSPredicate(format: "%K == nil", finishedKey)
        let optionalFilter = NSPredicate(format: "%K == 1", optionalKey)
        let unfinishedOrFinishedToday = NSCompoundPredicate(orPredicateWithSubpredicates: [unfinished, finishedToday])
        let expiredYesterday = NSPredicate(day: NSDate().dateByAddingTimeInterval(-24*60*60), dateKey: expiredKey)
        let notExpired = NSCompoundPredicate(notPredicateWithSubpredicate: expiredYesterday)
        let notOptional = NSCompoundPredicate(notPredicateWithSubpredicate: optionalFilter)
        let calendar = NSCalendar.currentCalendar()
        let tomorrow = calendar.startOfDayForDate(NSDate().dateByAddingTimeInterval(24*60*60))
        let notFuture = NSPredicate(format: "%K == nil OR %K < %@", scheduledKey, scheduledKey, tomorrow)
        
        switch section {
            
        case .ExpiredYesterday:
            // expired yesterday section only showns those expired tasks that are also unfinished
            return NSCompoundPredicate(andPredicateWithSubpredicates: [unfinished, expiredYesterday])
            
        case .Today:
            return NSCompoundPredicate(andPredicateWithSubpredicates: [notOptional, notFuture, unfinishedOrFinishedToday, notExpired])
            
        case .KeepGoing:
            // Keep going section includes optional tasks that are either unfinished or were finished today
            return NSCompoundPredicate(andPredicateWithSubpredicates: [optionalFilter, notFuture,unfinishedOrFinishedToday, notExpired])
        
        case .Tomorrow:
            // scheduled for tomorrow only
            return NSPredicate(day: NSDate().dateByAddingTimeInterval(24*60*60), dateKey: scheduledKey)
            
        default:
            return nil
        }
    }<commit_msg>Fix scheduling filters<commit_after>//
//  SBAScheduledActivityManager.swift
//  BridgeAppSDK
//
//  Copyright © 2016 <NAME>. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1.  Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2.  Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3.  Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

import ResearchKit
import BridgeSDK

// TODO: syoung 04/14/2016 This is a WIP first draft of an implementation of schedule fetching that
// works for Lilly but is not complete for Parkinsons (which include a separate section for "keep going"
// activities *and* includes surveys that are build server-side (currently not supported by this implementation)


public enum SBAScheduledActivitySection {
    
    case None
    case ExpiredYesterday
    case Today
    case KeepGoing
    case Tomorrow
}

public protocol SBAScheduledActivityManagerDelegate: SBAAlertPresenter {
    func reloadTable(scheduledActivityManager: SBAScheduledActivityManager)
}

public class SBAScheduledActivityManager: NSObject, SBASharedInfoController, ORKTaskViewControllerDelegate {
    
    public weak var delegate: SBAScheduledActivityManagerDelegate?
    
    public var sections: [SBAScheduledActivitySection] = [.Today, .KeepGoing]
    public var activities: [SBBScheduledActivity] = []
    
    private var reloading: Bool = false
    public func reloadData() {
        
        // Exit early if already reloading activities. This can happen if the user flips quickly back and forth from
        // this tab to another tab.
        if (reloading) { return }
        reloading = true
        
        SBAUserBridgeManager.fetchChangesToScheduledActivities(activities, todayOnly: false) { [weak self] (obj, error) in
            guard (error == nil), let scheduledActivities = obj as? [SBBScheduledActivity] else { return }
            
            dispatch_async(dispatch_get_main_queue(), {
                self?.loadActivities(scheduledActivities)
                self?.reloading = false
            })
        }
    }
    
    public func loadActivities(scheduledActivities: [SBBScheduledActivity]) {
        
        // Filter out any sections that aren't shown
        let filters = sections.mapAndFilter({ filterPredicateForScheduledActivitySection($0) })
        let includedSections = NSCompoundPredicate(orPredicateWithSubpredicates: filters)
        
        // Filter the scheduled activities to only include those that *this* version of the app is designed
        // to be able to handle. Currently, that means only taskReference activities with an identifier that
        // maps to a known task.
        self.activities = scheduledActivities.filter({ (schedule) -> Bool in
            return taskReferenceForSchedule(schedule) != nil && includedSections.evaluateWithObject(schedule)
        })
        
        // reload table
        self.delegate?.reloadTable(self)
    }
    
    
    // MARK: Data Source Management
    
    public func numberOfSections() -> Int {
        return sections.count
    }
    
    public func numberOfRowsInSection(section: Int) -> Int {
        return scheduledActivitiesForSection(section).count
    }
    
    private func scheduledActivitySectionForTableSection(section: Int) -> SBAScheduledActivitySection {
        guard section < sections.count else { return .None }
        return sections[section]
    }
    
    private func scheduledActivitiesForSection(section: Int) ->[SBBScheduledActivity] {
        let scheduledActivitySection = scheduledActivitySectionForTableSection(section)
        guard let predicate = filterPredicateForScheduledActivitySection(scheduledActivitySection) else { return [] }
        return activities.filter({ predicate.evaluateWithObject($0) })
    }
    
    public func sectionTitle(section: Int) -> String? {
        
        // Always return nil for the first section and if there are no rows in the section
        guard section > 0 && scheduledActivitiesForSection(section).count > 0
        else {
            return nil
        }
        
        // Return default localized string for each section
        switch scheduledActivitySectionForTableSection(section) {
        case .ExpiredYesterday:
            return Localization.localizedString("SBA_ACTIVITY_YESTERDAY")
        case .Today:
            return Localization.localizedString("SBA_ACTIVITY_TODAY")
        case .KeepGoing:
            return Localization.localizedString("SBA_ACTIVITY_KEEP_GOING")
        case .Tomorrow:
            return Localization.localizedString("SBA_ACTIVITY_TOMORROW")
        default:
            return nil
        }
    }
    
    public func filterPredicateForScheduledActivitySection(section: SBAScheduledActivitySection) -> NSPredicate? {
        
        // syoung 05/06/2016 As of Swift 2.2, there is no equivalent to NSStringFromSelector
        let expiredKey = "expiresOn"
        let scheduledKey = "scheduledOn"
        let finishedKey = "finishedOn"
        let optionalKey = "persistent"
        
        // For unscheduled we need to also filter out those tasks that were finished prior to today
        let finishedToday = NSPredicate(day: NSDate(), dateKey: finishedKey)
        let unfinished = NSPredicate(format: "%K == nil", finishedKey)
        let optionalFilter = NSPredicate(format: "%K == 1", optionalKey)
        let unfinishedOrFinishedToday = NSCompoundPredicate(orPredicateWithSubpredicates: [unfinished, finishedToday])
        let expiredYesterday = NSPredicate(day: NSDate().dateByAddingTimeInterval(-24*60*60), dateKey: expiredKey)
        let notOptional = NSCompoundPredicate(notPredicateWithSubpredicate: optionalFilter)
        let calendar = NSCalendar.currentCalendar()
        let tomorrow = calendar.startOfDayForDate(NSDate().dateByAddingTimeInterval(24*60*60))
        let today = calendar.startOfDayForDate(NSDate())
        let notFuture = NSPredicate(format: "%K == nil OR %K < %@", scheduledKey, scheduledKey, tomorrow)
        let notExpired = NSPredicate(format: "%K == nil OR %K > %@", expiredKey, expiredKey, today)
        
        switch section {
            
        case .ExpiredYesterday:
            // expired yesterday section only showns those expired tasks that are also unfinished
            return NSCompoundPredicate(andPredicateWithSubpredicates: [unfinished, expiredYesterday])
            
        case .Today:
            return NSCompoundPredicate(andPredicateWithSubpredicates: [notOptional, notFuture, unfinishedOrFinishedToday, notExpired])
            
        case .KeepGoing:
            // Keep going section includes optional tasks that are either unfinished or were finished today
            return NSCompoundPredicate(andPredicateWithSubpredicates: [optionalFilter, notFuture, unfinished, notExpired])
        
        case .Tomorrow:
            // scheduled for tomorrow only
            return NSPredicate(day: NSDate().dateByAddingTimeInterval(24*60*60), dateKey: scheduledKey)
            
        default:
            return nil
        }
    }
{'fraction_non_alphanumeric': 0.06714429510332169, 'fraction_numerical': 0.005684173130439931, 'mean_word_length': 3.015691868758916, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1780743', 'n_tokens_mistral': 4347, 'n_tokens_neox': 4106, 'n_words': 1468}