OSDN Git Service

#keyPathが使用可能な部分で全て使用するようにした
[kcd/KCD.git] / KCD / TimeSignalNotifier.swift
1 //
2 //  TimeSignalNotifier.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/01/21.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 extension Selector {
12     static let fire = #selector(TimeSignalNotifier.fire(_:))
13 }
14
15 class TimeSignalNotifier: NSObject {
16     let udController: NSUserDefaultsController = NSUserDefaultsController.shared()
17     
18     override init() {
19         super.init()
20         registerTimer()
21         self.bind(#keyPath(notifyTimeBeforeTimeSignal),
22                   to: udController,
23                   withKeyPath: "values.notifyTimeBeforeTimeSignal")
24     }
25     deinit {
26         self.unbind(#keyPath(notifyTimeBeforeTimeSignal))
27     }
28     
29     dynamic var notifyTimeBeforeTimeSignal: Int = 0 {
30         didSet { registerTimer() }
31     }
32     var timer: Timer?
33     
34     func fire(_ timer: Timer) {
35         defer { registerTimer() }
36         if !UserDefaults.standard.notifyTimeSignal { return }
37                 
38         let now = Date()
39         let cal = Calendar.current
40         let minutes = cal.component(.minute, from: now)
41         
42         if (59 - minutes) > notifyTimeBeforeTimeSignal { return }
43         
44         let notification = NSUserNotification()
45         let hour = cal.component(.hour, from: now)
46         let format = NSLocalizedString("It is soon %zd o'clock.",
47                                        comment: "It is soon %zd o'clock.")
48         notification.title = String(format: format, hour + 1)
49         notification.informativeText = notification.title
50         if UserDefaults.standard.playNotifyTimeSignalSound {
51             notification.soundName = NSUserNotificationDefaultSoundName
52         }
53         NSUserNotificationCenter.default.deliver(notification)
54     }
55     
56     private func registerTimer() {
57         timer?.invalidate()
58         
59         let now = Date()
60         let cal = Calendar.current
61         var comp = cal.dateComponents([.year, .month, .day, .hour], from: now)
62         let minutes = cal.component(.minute, from: now)
63         if minutes + notifyTimeBeforeTimeSignal >= 60 {
64             comp.hour = comp.hour.map { $0 + 1 }
65         }
66         comp.minute = 60 - notifyTimeBeforeTimeSignal
67         guard let notifyDate = cal.date(from: comp)
68             else { return print("Can not create notify date") }
69         timer = Timer.scheduledTimer(timeInterval: notifyDate.timeIntervalSinceNow,
70                                      target: self,
71                                      selector: .fire,
72                                      userInfo: nil,
73                                      repeats: false)
74     }
75 }