OSDN Git Service

d46847b01d4e879e5ca923bdf265a5d023e7ffdb
[kcd/KCD.git] / KCD / MasterShipMapper.swift
1 //
2 //  MasterShipMapper.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/22.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 class MasterShipMapper: JSONMapper {
12     let apiResponse: APIResponse
13     let configuration = MappingConfiguration(entityType: MasterShip.self,
14                                              dataKey: "api_data.api_mst_ship",
15                                              editorStore: ServerDataStore.oneTimeEditor())
16     
17     required init(_ apiResponse: APIResponse) {
18         self.apiResponse = apiResponse
19     }
20     
21     private lazy var masterSTypes: [MasterSType] = {
22         return ServerDataStore.default.sortedMasterSTypesById()
23     }()
24     
25     func handleExtraValue(_ value: Any, forKey key: String, to object: NSManagedObject) -> Bool {
26         if key != "api_stype" { return false }
27         
28         guard let sType = value as? Int
29             else {
30                 print("MasterShipMapper: value is not Int")
31                 return false
32         }
33         guard let masterShip = object as? MasterShip
34             else {
35                 print("MasterShipMapper: object is not KCMasterShipObject")
36                 return false
37         }
38         setStype(sType, to: masterShip)
39         return true
40     }
41     
42     private func setStype(_ stypeID: Int, to masterShip: MasterShip) {
43         if masterShip.stype.id == stypeID { return }
44         guard let stype = masterSTypes.binarySearch(comparator: { $0.id ==? stypeID })
45             else { return print("MasterShipMapper: Can not find MasterSType") }
46         guard let masterSType = configuration.editorStore.object(with: stype.objectID) as? MasterSType
47             else { return print("MasterShipMapper: Can not convert to current moc object masterSType") }
48         masterShip.stype = masterSType
49     }
50 }