//
//  AppDelegate.swift
//  ActionableNotifications
//
//  Created by Jeff Kelley on 4/26/15.
//  Copyright (c) 2015 Pragmatic Bookshelf. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        registerNotificationCategories()
        return true
    }

    func registerNotificationCategories() {
        let acceptAction = UIMutableUserNotificationAction()
        
        acceptAction.activationMode = .Background
        acceptAction.authenticationRequired = true
        acceptAction.identifier = "Accept"
        acceptAction.title = "Accept"
        
        let declineAction = UIMutableUserNotificationAction()
        
        declineAction.activationMode = .Background
        declineAction.authenticationRequired = true
        declineAction.identifier = "Decline"
        declineAction.title = "Decline"
        
        let maybeAction = UIMutableUserNotificationAction()
        
        maybeAction.activationMode = .Background
        maybeAction.authenticationRequired = true
        maybeAction.identifier = "Maybe"
        maybeAction.title = "Maybe"
        
        let deleteAction = UIMutableUserNotificationAction()
        
        deleteAction.activationMode = .Background
        deleteAction.authenticationRequired = true
        deleteAction.destructive = true
        deleteAction.identifier = "Delete"
        deleteAction.title = "Delete"

        let category = UIMutableUserNotificationCategory() 
        
        category.identifier = "Invitation"
        
        category.setActions([acceptAction, declineAction], forContext: .Minimal) 

        category.setActions([acceptAction, maybeAction, declineAction, deleteAction],  
            forContext: .Default)
        
        let categories: Set<NSObject> = [category]

        let settings = UIUserNotificationSettings(forTypes: .Alert,
            categories: categories)
        
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    }

    func application(application: UIApplication,
        handleActionWithIdentifier identifier: String?,
        forLocalNotification notification: UILocalNotification,
        completionHandler: () -> Void) {
        if notification.category == "Invitation" {
            if identifier == "Accept" {
                // Handle accepted invitation
            }
            else if identifier == "Maybe" {
                // Handle tentative response
            }
            else if identifier == "Decline" {
                // Handle declined invitation
            }
            else if identifier == "Delete" {
                // Delete invitation
            }
        }
        
        completionHandler()
    }
}
