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())
26 private enum SlotItemAPI: String {
28 case getMemberSlotItem = "/kcsapi/api_get_member/slot_item"
29 case kousyouGetShip = "/kcsapi/api_req_kousyou/getship"
30 case getMemberRequireInfo = "/kcsapi/api_get_member/require_info"
33 private class func dataKeys(_ apiResponse: APIResponse) -> [String] {
35 guard let slotItemApi = SlotItemAPI(rawValue: apiResponse.api) else { return ["api_data"] }
38 case .kousyouGetShip: return ["api_data", "api_slotitem"]
40 case .getMemberRequireInfo: return ["api_data", "api_slot_item"]
42 case .getMemberSlotItem: return ["api_data"]
46 private var registerIds: [Int] = []
47 private lazy var masterSlotItems: [MasterSlotItem] = {
48 return ServerDataStore.default.sortedMasterSlotItemsById()
51 func beginRegister(_ slotItem: SlotItem) {
56 func handleExtraValue(_ value: JSON, forKey key: String, to object: SlotItem) -> Bool {
58 // 取得後破棄した装備のデータを削除するため保有IDを保存
61 guard let id = value.int else { return false }
63 registerIds.append(id)
68 if key == "api_slotitem_id" {
70 guard let id = value.int else { return false }
72 setMaster(id, to: object)
80 func finishOperating() {
82 // getshipの時は取得した艦娘の装備のみのデータのため無視
83 if let slotItemApi = SlotItemAPI(rawValue: apiResponse.api),
84 slotItemApi == .kousyouGetShip {
90 guard let store = configuration.editorStore as? ServerDataStore else { return }
92 store.slotItems(exclude: registerIds).forEach { store.delete($0) }
95 private func setMaster(_ masterId: Int, to slotItem: SlotItem?) {
97 guard let slotItem = slotItem else { return }
99 if slotItem.slotitem_id == masterId { return }
101 guard let mSlotItem = masterSlotItems.binarySearch(comparator: { $0.id ==? masterId }) else {
103 print("Can not find MasterSlotItem")
107 guard let moc = slotItem.managedObjectContext,
108 let masterSlotItem = moc.object(with: mSlotItem.objectID) as? MasterSlotItem else {
110 print("Can not convert to current moc object")
114 slotItem.master_slotItem = masterSlotItem
115 slotItem.slotitem_id = masterId