OSDN Git Service

関数名を変更
[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 final class TimeSignalNotifier: NSObject {
12     
13     let udController: NSUserDefaultsController = NSUserDefaultsController.shared
14     
15     override init() {
16         
17         super.init()
18         
19         registerTimer()
20         bind(NSBindingName(#keyPath(notifyTimeBeforeTimeSignal)),
21              to: udController,
22              withKeyPath: "values.notifyTimeBeforeTimeSignal")
23     }
24     
25     deinit {
26         
27         unbind(NSBindingName(#keyPath(notifyTimeBeforeTimeSignal)))
28     }
29     
30     @objc dynamic var notifyTimeBeforeTimeSignal: Int = 0 {
31         
32         didSet { registerTimer() }
33     }
34     var timer: Timer?
35     
36     @objc func fire(_ timer: Timer) {
37         
38         defer { registerTimer() }
39         
40         guard UserDefaults.standard[.notifyTimeSignal] else { return }
41         
42         let now = Date()
43         let cal = Calendar.current
44         let minutes = cal.component(.minute, from: now)
45         
46         if (59 - minutes) > notifyTimeBeforeTimeSignal { return }
47         
48         let notification = NSUserNotification()
49         let hour = cal.component(.hour, from: now)
50         let format = LocalizedStrings.timerSIgnalMessage.string
51         notification.title = String(format: format, hour + 1)
52         notification.informativeText = notification.title
53         
54         if UserDefaults.standard[.playNotifyTimeSignalSound] {
55             
56             notification.soundName = NSUserNotificationDefaultSoundName
57         }
58         
59         NSUserNotificationCenter.default.deliver(notification)
60     }
61     
62     private func registerTimer() {
63         
64         timer?.invalidate()
65         
66         let now = Date()
67         let cal = Calendar.current
68         var comp = cal.dateComponents([.year, .month, .day, .hour], from: now)
69         let minutes = cal.component(.minute, from: now)
70         if minutes + notifyTimeBeforeTimeSignal >= 60 {
71             
72             comp.hour = comp.hour.map { $0 + 1 }
73         }
74         comp.minute = 60 - notifyTimeBeforeTimeSignal
75         guard let notifyDate = cal.date(from: comp) else {
76             
77             return Logger.shared.log("Can not create notify date")
78         }
79         
80         timer = Timer.scheduledTimer(timeInterval: notifyDate.timeIntervalSinceNow,
81                                      target: self,
82                                      selector: #selector(TimeSignalNotifier.fire(_:)),
83                                      userInfo: nil,
84                                      repeats: false)
85     }
86 }