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