2 // MaterialMapper.swift
5 // Created by Hori,Masaki on 2017/02/24.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
12 final class MaterialMapper: JSONMapper {
14 let apiResponse: APIResponse
15 let configuration: MappingConfiguration<Material>
18 #keyPath(Material.fuel), #keyPath(Material.bull), #keyPath(Material.steel), #keyPath(Material.bauxite),
19 #keyPath(Material.kousokukenzo), #keyPath(Material.kousokushuhuku), #keyPath(Material.kaihatusizai), #keyPath(Material.screw)
22 required init(_ apiResponse: APIResponse) {
24 self.apiResponse = apiResponse
25 self.configuration = MappingConfiguration(entity: Material.self,
26 dataKeys: MaterialMapper.dataKeys(apiResponse),
27 editorStore: ServerDataStore.oneTimeEditor())
30 private class func dataKeys(_ apiResponse: APIResponse) -> [String] {
32 switch apiResponse.api.endpoint {
34 case .material: return ["api_data"]
36 case .port, .createItem, .destroyShip, .charge: return ["api_data", "api_material"]
38 case .remodelSlot: return ["api_data", "api_after_material"]
42 Logger.shared.log("Missing API: \(apiResponse.api)")
50 configuration.editorStore.sync(execute: commintInContext)
53 private func commintInContext() {
55 guard let store = configuration.editorStore as? ServerDataStore,
56 let material = store.material() ?? store.createMaterial() else {
58 Logger.shared.log("Can not create Material")
63 if let _ = data[0].int {
65 let array = data.arrayValue.compactMap { $0.int }
66 register(material, data: array)
68 } else if let _ = data[0].dictionary {
70 register(material, data: data.arrayValue)
74 print("JSON is unknown type")
79 private func register(_ material: Material, data: [Int]) {
81 zip(data, keys).forEach {
83 material.setValue($0, forKey: $1)
87 private func register(_ material: Material, data: [JSON]) {
91 guard let i = $0["api_id"].int, case 1...keys.count = i else {
95 guard let newValue = $0["api_value"].int else {
100 material.setValue(newValue as NSNumber, forKey: keys[i - 1])