2 // SlotItemMapper.swift
5 // Created by Hori,Masaki on 2017/02/25.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 fileprivate enum SlotItemAPI: String {
13 case getMemberSlotItem = "/kcsapi/api_get_member/slot_item"
14 case kousyouGetShip = "/kcsapi/api_req_kousyou/getship"
15 case getMemberRequireInfo = "/kcsapi/api_get_member/require_info"
18 fileprivate func dataKeys(_ apiResponse: APIResponse) -> [String] {
19 guard let slotItemApi = SlotItemAPI(rawValue: apiResponse.api)
20 else { return ["api_data"] }
22 case .kousyouGetShip: return ["api_data", "api_slotitem"]
23 case .getMemberRequireInfo: return ["api_data", "api_slot_item"]
24 default: return ["api_data"]
28 class SlotItemMapper: JSONMapper {
29 typealias ObjectType = SlotItem
31 let apiResponse: APIResponse
32 let configuration: MappingConfiguration<SlotItem>
34 required init(_ apiResponse: APIResponse) {
35 self.apiResponse = apiResponse
36 self.configuration = MappingConfiguration(entity: SlotItem.entity,
37 dataKeys: dataKeys(apiResponse),
38 editorStore: ServerDataStore.oneTimeEditor())
41 private var registerIds: [Int] = []
42 private lazy var masterSlotItems: [MasterSlotItem] = {
43 return ServerDataStore.default.sortedMasterSlotItemsById()
46 func beginRegister(_ slotItem: SlotItem) {
49 func handleExtraValue(_ value: JSON, forKey key: String, to object: SlotItem) -> Bool {
50 // 取得後破棄した装備のデータを削除するため保有IDを保存
52 guard let id = value.int
54 registerIds.append(id)
58 if key == "api_slotitem_id" {
59 guard let id = value.int
61 setMaster(id, to: object)
66 func finishOperating() {
67 // getshipの時は取得した艦娘の装備のみのデータのため無視
68 if let slotItemApi = SlotItemAPI(rawValue: apiResponse.api),
69 slotItemApi == .kousyouGetShip {
72 guard let store = configuration.editorStore as? ServerDataStore
74 store.slotItems(exclude: registerIds).forEach { store.delete($0) }
77 private func setMaster(_ masterId: Int, to slotItem: SlotItem?) {
78 guard let slotItem = slotItem
80 if slotItem.slotitem_id == masterId { return }
82 guard let mSlotItem = masterSlotItems.binarySearch(comparator: { $0.id ==? masterId })
83 else { return print("Can not find MasterSlotItem") }
84 guard let moc = slotItem.managedObjectContext,
85 let masterSlotItem = moc.object(with: mSlotItem.objectID) as? MasterSlotItem
86 else { return print("Can not convert to current moc object") }
87 slotItem.master_slotItem = masterSlotItem
88 slotItem.slotitem_id = masterId