OSDN Git Service

ShipMapperにslotDepriveの時用のイニシャライザを追加
[kcd/KCD.git] / KCD / ShipMapper.swift
1 //
2 //  ShipMapper.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/23.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10 import SwiftyJSON
11
12 final class ShipMapper: JSONMapper {
13     
14     private static let ignoreKeys = ["api_gomes", "api_gomes2", "api_broken", "api_powup",
15                                      "api_voicef", "api_afterlv", "api_aftershipid", "api_backs",
16                                      "api_slotnum", "api_stype", "api_name", "api_yomi",
17                                      "api_raig", "api_luck", "api_saku", "api_raim", "api_baku",
18                                      "api_taik", "api_houg", "api_houm", "api_tyku",
19                                      "api_ndock_item", "api_star",
20                                      "api_ndock_time_str", "api_member_id",
21                                      "api_fuel_max", "api_bull_max"]
22     
23     let apiResponse: APIResponse
24     let configuration: MappingConfiguration<Ship>
25     
26     required init(_ apiResponse: APIResponse) {
27         
28         self.apiResponse = apiResponse
29         self.configuration = MappingConfiguration(entity: Ship.entity,
30                                                   dataKeys: ShipMapper.dataKeys(apiResponse),
31                                                   editorStore: ServerDataStore.oneTimeEditor(),
32                                                   ignoreKeys: ShipMapper.ignoreKeys)
33     }
34     
35     // slotDepriveの時に2種類のデータが来るため
36     init(forSlotDepriveUnset apiResponse: APIResponse) {
37         
38         self.apiResponse = apiResponse
39         self.configuration = MappingConfiguration(entity: Ship.entity,
40                                                   dataKeys: ["api_data", "api_ship_data", "api_unset_ship"],
41                                                   editorStore: ServerDataStore.oneTimeEditor(),
42                                                   ignoreKeys: ShipMapper.ignoreKeys)
43     }
44     
45     private class func dataKeys(_ apiResponse: APIResponse) -> [String] {
46         
47         switch apiResponse.api.endpoint {
48             
49         case .port, .getShip, .powerup: return ["api_data", "api_ship"]
50             
51         case .ship3, .shipDeck: return ["api_data", "api_ship_data"]
52             
53         case .slotDeprive: return ["api_data", "api_ship_data", "api_set_ship"]
54             
55         case .ship: return ["api_data"]
56             
57         default: return Logger.shared.log("Missing API: \(apiResponse.api)", value: ["api_data"])
58         }
59     }
60     
61     private var registerIds: [Int] = []
62     private lazy var masterShips: [MasterShip] = {
63         
64         return ServerDataStore.default.sortedMasterShipsById()
65     }()
66     private lazy var slotItems: [SlotItem] = {
67         
68         return ServerDataStore.default.sortedSlotItemsById()
69     }()
70     private var isDeleteNotExist: Bool {
71         
72         switch apiResponse.api.endpoint {
73         case .ship3, .getShip, .shipDeck,
74              .powerup, .slotDeprive:
75             return false
76             
77         default:
78             return true
79         }
80     }
81     
82     private var store: ServerDataStore? {
83         
84         return configuration.editorStore as? ServerDataStore
85     }
86     
87     func beginRegister(_ ship: Ship) {
88         
89         ship.sally_area = nil
90     }
91     
92     func handleExtraValue(_ value: JSON, forKey key: String, to ship: Ship) -> Bool {
93         
94         // 取得後破棄した装備のデータを削除するため保有IDを保存
95         if key == "api_id" {
96             
97             guard let id = value.int else { return false }
98             
99             registerIds.append(id)
100             
101             return false
102         }
103         
104         if key == "api_ship_id" {
105             
106             guard let masterId = value.int else { return false }
107             
108             setMaster(masterId, to: ship)
109             
110             return true
111         }
112         
113         if key == "api_exp" {
114             
115             guard let exp = value[0].int else { return false }
116             
117             ship.exp = exp
118             
119             return true
120         }
121         
122         if key == "api_slot" {
123             
124             setSlot(value, to: ship)
125             
126             return false
127         }
128         
129         if key == "api_slot_ex" {
130             
131             guard let ex = value.int else { return false }
132             
133             setExtraSlot(ex, to: ship)
134             
135             return false
136         }
137         
138         return false
139     }
140     
141     func finishOperating() {
142         
143         if !isDeleteNotExist { return }
144         
145         store?.ships(exclude: registerIds).forEach { store?.delete($0) }
146     }
147     
148     private func setMaster(_ masterId: Int, to ship: Ship) {
149         
150         if ship.ship_id == masterId { return }
151         
152         guard let mShip = masterShips.binarySearch(comparator: { $0.id ==? masterId }),
153             let masterShip = store?.object(of: MasterShip.entity, with: mShip.objectID) else {
154                 
155                 return Logger.shared.log("Can not convert to current moc object masterShip")
156         }
157         
158         ship.master_ship = masterShip
159         ship.ship_id = masterId
160     }
161     
162     private func setSlot(_ slotItems: JSON, to ship: Ship) {
163         
164         guard let converSlotItems = slotItems.arrayObject as? [Int] else { return }
165         guard let store = store else { return }
166         
167         let newItems: [SlotItem] =
168             converSlotItems.flatMap { item in
169                 
170                 if item == 0 || item == -1 { return nil }
171                 
172                 guard let found = self.slotItems.binarySearch(comparator: { $0.id ==? item }),
173                     let slotItem = store.object(of: SlotItem.entity, with: found.objectID) else {
174                         
175                         let maxV = converSlotItems.last
176                         if maxV != nil, maxV! < item {
177                             
178                             Debug.print("item is maybe unregistered, so it is new ship's equipment.")
179                             return nil
180                         }
181                         Logger.shared.log("Can not convert to current moc object slotItem")
182                         return nil
183                 }
184                 
185                 return slotItem
186         }
187         
188         ship.equippedItem = NSOrderedSet(array: newItems)
189     }
190     
191     private func setExtraSlot(_ exSlotItem: Int, to ship: Ship) {
192         
193         guard exSlotItem != -1, exSlotItem != 0 else { return }
194         guard let found = slotItems.binarySearch(comparator: { $0.id ==? exSlotItem }),
195             let ex = store?.object(of: SlotItem.entity, with: found.objectID) else {
196                 
197                 return Logger.shared.log("Can not convert to current moc object")
198         }
199         
200         ship.extraItem = ex
201     }
202 }