2 // GuardShelterCommand.swift
5 // Created by Hori,Masaki on 2017/01/15.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 enum GuardEscapeAPI: String {
14 case goback = "/kcsapi/api_req_combined_battle/goback_port"
17 extension Notification.Name {
19 static let DidUpdateGuardEscape = Notification.Name("com.masakih.KCD.Notification.DidUpdateGuardEscape")
22 final class GuardShelterCommand: JSONCommand {
24 override class func canExecuteAPI(_ api: String) -> Bool {
26 return GuardEscapeAPI(rawValue: api) != nil ? true : false
29 override func execute() {
31 if let b = BattleAPI(rawValue: api) {
34 case .battleResult, .combinedBattleResult:
41 if let m = MapAPI(rawValue: api), m == .next {
45 if let _ = GuardEscapeAPI(rawValue: api) {
49 if let _ = PortAPI(rawValue: api) {
55 private func damagedShipId(damagedPos: Int) -> Int? {
57 let store = ServerDataStore.default
60 case 1...6: return store.deck(by: 1)?.shipId(of:damagedPos - 1)
61 case 7...12: return store.deck(by: 2)?.shipId(of: damagedPos - 6 - 1)
66 private func registerReserve() {
68 let escape = data["api_escape"]
70 guard let guardianPos = escape["api_tow_idx"][0].int else { return }
72 let fixedGuardianPos = guardianPos - 6 - 1
74 guard let guardianId = ServerDataStore.default.deck(by: 2)?.shipId(of: fixedGuardianPos) else {
76 print("guardianPos is wrong")
80 guard let escapeIdx = escape["api_escape_idx"][0].int,
81 let damagedId = damagedShipId(damagedPos: escapeIdx) else {
83 print("damagedPos is wrong")
87 let store = TemporaryDataStore.oneTimeEditor()
89 guard let guardian = store.createGuardEscaped() else {
91 print("Can not create GuardEscaped for guardinan")
95 guardian.shipID = guardianId
96 guardian.ensured = false
98 guard let damaged = store.createGuardEscaped() else {
100 print("Can not create GuardEscaped for damaged")
104 damaged.shipID = damagedId
105 damaged.ensured = false
108 private func removeInvalidEntry() {
110 let store = TemporaryDataStore.oneTimeEditor()
112 store.notEnsuredGuardEscaped().forEach(store.delete)
114 Thread.sleep(forTimeInterval: 0.1)
118 private func removeAllEntry() {
120 let store = TemporaryDataStore.oneTimeEditor()
122 store.guardEscaped().forEach(store.delete)
124 Thread.sleep(forTimeInterval: 0.1)
128 func ensureGuardShelter() {
130 let store = TemporaryDataStore.oneTimeEditor()
132 store.guardEscaped().forEach { $0.ensured = true }
134 Thread.sleep(forTimeInterval: 0.1)
138 private func notify() {
140 DispatchQueue.main.async {
142 NotificationCenter.default.post(name: .DidUpdateGuardEscape, object: self)