2 // SlotItemMapper.swift
5 // Created by Hori,Masaki on 2017/02/25.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 final class SlotItemMapper: JSONMapper {
14 let apiResponse: APIResponse
15 let configuration: MappingConfiguration<SlotItem>
17 required init(_ apiResponse: APIResponse) {
19 self.apiResponse = apiResponse
20 self.configuration = MappingConfiguration(entity: SlotItem.self,
21 dataKeys: SlotItemMapper.dataKeys(apiResponse),
22 editorStore: ServerDataStore.oneTimeEditor())
25 private class func dataKeys(_ apiResponse: APIResponse) -> [String] {
27 switch apiResponse.api.endpoint {
29 case .getShip: return ["api_data", "api_slotitem"]
31 case .requireInfo: return ["api_data", "api_slot_item"]
33 case .slotItem: return ["api_data"]
37 Logger.shared.log("Missing API: \(apiResponse.api)")
44 private var registerIds: [Int] = []
45 private lazy var masterSlotItems: [MasterSlotItem] = {
47 guard let store = configuration.editorStore as? ServerDataStore else {
52 return store.sortedMasterSlotItemsById()
55 func beginRegister(_ slotItem: SlotItem) {
60 func handleExtraValue(_ value: JSON, forKey key: String, to object: SlotItem) -> Bool {
62 // 取得後破棄した装備のデータを削除するため保有IDを保存
65 guard let id = value.int else {
70 registerIds.append(id)
75 if key == "api_slotitem_id" {
77 guard let id = value.int else {
82 setMaster(id, to: object)
90 func finishOperating() {
92 // getshipの時は取得した艦娘の装備のみのデータのため無視
93 if apiResponse.api.endpoint == .getShip {
98 guard let store = configuration.editorStore as? ServerDataStore else {
103 store.slotItems(exclude: registerIds).forEach(store.delete)
106 private func setMaster(_ masterId: Int, to slotItem: SlotItem?) {
108 guard let slotItem = slotItem else {
113 if slotItem.slotitem_id == masterId {
118 guard let mSlotItem = masterSlotItems.binarySearch(comparator: { $0.id ==? masterId }) else {
120 Logger.shared.log("Can not find MasterSlotItem")
125 // FUCK: 型推論がバカなのでダウンキャストしてるんだ!!!
126 guard let masterSlotItem = configuration.editorStore.exchange(mSlotItem) as? MasterSlotItem else {
128 Logger.shared.log("Can not convert to current moc object")
133 slotItem.master_slotItem = masterSlotItem
134 slotItem.slotitem_id = masterId