OSDN Git Service

Doutakuを導入
[kcd/KCD.git] / KCD / ShipSlotObserver.swift
1 //
2 //  ShipSlotObserver.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/12/31.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 protocol ShipSlotObserverDelegate: class {
12     
13     func didChangeSlot0()
14     func didChangeSlot1()
15     func didChangeSlot2()
16     func didChangeSlot3()
17     func didChangeSlot4()
18 }
19
20 class ShipSlotObserver: NSObject {
21     
22     private enum SlotPosition {
23         case first
24         case second
25         case third
26         case fourth
27         case fifth
28     }
29     
30     private let ship: Ship
31     
32     weak var delegate: ShipSlotObserverDelegate?
33     
34     private var observations: [NSKeyValueObservation] = []
35     
36     init(ship: Ship) {
37         
38         self.ship = ship
39         
40         super.init()
41         
42         observeSlot()
43         observeOnSlot()
44     }
45     
46     private func observeSlot() {
47         
48         let keyPaths = [\Ship.slot_0, \Ship.slot_1, \Ship.slot_2, \Ship.slot_3, \Ship.slot_4]
49         observe(keyPaths: keyPaths)
50     }
51     
52     private func observeOnSlot() {
53         
54         let keyPaths = [\Ship.onslot_0, \Ship.onslot_1, \Ship.onslot_2, \Ship.onslot_3, \Ship.onslot_4]
55         observe(keyPaths: keyPaths)
56     }
57     
58     private func observe(keyPaths: [KeyPath<Ship, Int>]) {
59         
60         let positions: [SlotPosition] = [.first, .second, .third, .fourth, .fifth]
61         
62         observations += zip(keyPaths, positions)
63             .map { [weak self] keyPath, position in
64                 ship.observe(keyPath) { _, _ in
65                     self?.notifyChange(on: position)
66                 }
67         }
68     }
69     
70     private func notifyChange(on position: SlotPosition) {
71         
72         switch position {
73             
74         case .first: delegate?.didChangeSlot0()
75         case .second: delegate?.didChangeSlot1()
76         case .third: delegate?.didChangeSlot2()
77         case .fourth: delegate?.didChangeSlot3()
78         case .fifth: delegate?.didChangeSlot4()
79         }
80     }
81 }