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.entity,
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"]
35 default: return Logger.shared.log("Missing API: \(apiResponse.api)", value: ["api_data"])
39 private var registerIds: [Int] = []
40 private lazy var masterSlotItems: [MasterSlotItem] = {
41 return ServerDataStore.default.sortedMasterSlotItemsById()
44 func beginRegister(_ slotItem: SlotItem) {
49 func handleExtraValue(_ value: JSON, forKey key: String, to object: SlotItem) -> Bool {
51 // 取得後破棄した装備のデータを削除するため保有IDを保存
54 guard let id = value.int else { return false }
56 registerIds.append(id)
61 if key == "api_slotitem_id" {
63 guard let id = value.int else { return false }
65 setMaster(id, to: object)
73 func finishOperating() {
75 // getshipの時は取得した艦娘の装備のみのデータのため無視
76 if apiResponse.api.endpoint == .getShip {
81 guard let store = configuration.editorStore as? ServerDataStore else { return }
83 store.slotItems(exclude: registerIds).forEach(store.delete)
86 private func setMaster(_ masterId: Int, to slotItem: SlotItem?) {
88 guard let slotItem = slotItem else { return }
90 if slotItem.slotitem_id == masterId { return }
92 guard let mSlotItem = masterSlotItems.binarySearch(comparator: { $0.id ==? masterId }) else {
94 return Logger.shared.log("Can not find MasterSlotItem")
97 guard let masterSlotItem = configuration.editorStore.object(of: MasterSlotItem.entity, with: mSlotItem.objectID) else {
99 return Logger.shared.log("Can not convert to current moc object")
102 slotItem.master_slotItem = masterSlotItem
103 slotItem.slotitem_id = masterId