OSDN Git Service

アクションをdelegateではなくfirst responder に接続した
[kcd/KCD.git] / KCD / KenzoDockStatus.swift
1 //
2 //  KenzoDockStatus.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/01/22.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 fileprivate enum DockState: Int {
12     case empty = 0
13     case hasShip = 2
14     case completed = 3
15     case notOpen = -1
16 }
17
18 class KenzoDockStatus: NSObject {
19     private let number: Int
20     private let controller: NSArrayController
21     private var isTasking = false
22     private var didNotify = false
23     private var realTime: TimeInterval = 0.0 {
24         didSet { time = realTime as NSNumber }
25     }
26     dynamic var time: NSNumber?
27     dynamic var state: NSNumber? {
28         didSet {
29             guard let state = state as? Int,
30                 let s = DockState(rawValue: state)
31                 else { return print("unknown State") }
32             switch s {
33             case .empty, .notOpen:
34                 isTasking = false
35                 didNotify = false
36             case .hasShip, .completed:
37                 isTasking = true
38             }
39         }
40     }
41     
42     init?(number: Int) {
43         guard 1...4 ~= number else { return nil }
44         self.number = number
45         controller = NSArrayController()
46         super.init()
47         controller.managedObjectContext = ServerDataStore.default.managedObjectContext
48         controller.entityName = KenzoDock.entityName
49         controller.fetchPredicate = NSPredicate(format: "id = %ld", number)
50         controller.automaticallyRearrangesObjects = true
51         controller.fetch(nil)
52         
53         bind("state", to: controller, withKeyPath: "selection.state")
54     }
55     
56     func update() {
57         if !isTasking {
58             time = nil
59             return
60         }
61         guard let t = controller.value(forKeyPath: "selection.complete_time") as? Int
62             else {
63                 time = nil
64                 return
65         }
66         let compTime = TimeInterval(Int(t / 1_000))
67         let now = Date()
68         let diff = compTime - now.timeIntervalSince1970
69         
70         realTime = diff < 0 ? 0 : diff
71         
72         if didNotify { return }
73         if diff > 0 { return }
74         
75         let notification = NSUserNotification()
76         let format = NSLocalizedString("It Will Finish Build at No.%@.", comment: "It Will Finish Build at No.%@.")
77         notification.title = String(format: format, number as NSNumber)
78         notification.informativeText = notification.title
79         if UserDefaults.standard.playFinishKenzoSound {
80             notification.soundName = NSUserNotificationDefaultSoundName
81         }
82         NSUserNotificationCenter.default.deliver(notification)
83         didNotify = true
84     }
85     
86 }