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 else { return false }
53 registerIds.append(id)
57 if key == "api_slotitem_id" {
58 guard let id = value.int else { return false }
59 setMaster(id, to: object)
64 func finishOperating() {
65 // getshipの時は取得した艦娘の装備のみのデータのため無視
66 if let slotItemApi = SlotItemAPI(rawValue: apiResponse.api),
67 slotItemApi == .kousyouGetShip {
70 guard let store = configuration.editorStore as? ServerDataStore
72 store.slotItems(exclude: registerIds).forEach { store.delete($0) }
75 private func setMaster(_ masterId: Int, to slotItem: SlotItem?) {
76 guard let slotItem = slotItem else { return }
77 if slotItem.slotitem_id == masterId { return }
79 guard let mSlotItem = masterSlotItems.binarySearch(comparator: { $0.id ==? masterId })
80 else { return print("Can not find MasterSlotItem") }
81 guard let moc = slotItem.managedObjectContext,
82 let masterSlotItem = moc.object(with: mSlotItem.objectID) as? MasterSlotItem
83 else { return print("Can not convert to current moc object") }
84 slotItem.master_slotItem = masterSlotItem
85 slotItem.slotitem_id = masterId