OSDN Git Service

72f82cd165e5b0bb9233e076a46f50d658be2b5b
[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 import SwiftyJSON
11
12 final class MasterShipMapper: JSONMapper {
13         
14     let apiResponse: APIResponse
15     let configuration = MappingConfiguration(entity: MasterShip.entity,
16                                              dataKeys: ["api_data", "api_mst_ship"],
17                                              editorStore: ServerDataStore.oneTimeEditor())
18     
19     required init(_ apiResponse: APIResponse) {
20         
21         self.apiResponse = apiResponse
22     }
23     
24     private lazy var masterSTypes: [MasterSType] = {
25         
26         guard let store = configuration.editorStore as? ServerDataStore else {
27             
28             return []
29         }
30         
31         return store.sortedMasterSTypesById()
32     }()
33     
34     func handleExtraValue(_ value: JSON, forKey key: String, to masterShip: MasterShip) -> Bool {
35         
36         if key != "api_stype" {
37             
38             return false
39         }
40         
41         guard let sType = value.int else {
42             
43             Logger.shared.log("MasterShipMapper: value is not Int")
44             
45             return false
46         }
47         
48         setStype(sType, to: masterShip)
49         
50         return true
51     }
52     
53     private func setStype(_ stypeID: Int, to masterShip: MasterShip) {
54         
55         if masterShip.stype.id == stypeID { return }
56         
57         guard let stype = masterSTypes.binarySearch(comparator: { $0.id ==? stypeID }) else {
58             
59             Logger.shared.log("MasterShipMapper: Can not find MasterSType")
60             
61             return
62         }
63         
64         // FUCK: 型推論がバカなのでダウンキャストしてるんだ!!!
65         guard let masterSType = configuration.editorStore.exchange(stype) as? MasterSType else {
66             
67             Logger.shared.log("MasterShipMapper: Can not convert to current moc object masterSType")
68             
69             return
70         }
71         
72         masterShip.stype = masterSType
73     }
74 }