OSDN Git Service

Squashed commit of the following: Swiftに変換した
[kcd/KCD.git] / KCD / AirBaseMapper.swift
1 //
2 //  AirBaseMapper.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/25.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 class AirBaseMapper: JSONMapper {
12     let apiResponse: APIResponse
13     let configuration = MappingConfiguration(entityName: "AirBase",
14                                              dataKey: "api_data.api_air_base",
15                                              compositPrimaryKeys: ["area_id", "rid"],
16                                              editorStore: ServerDataStore.oneTimeEditor())
17     
18     required init(_ apiResponse: APIResponse) {
19         self.apiResponse = apiResponse
20     }
21
22     func handleExtraValue(_ value: Any, forKey key: String, to object: NSManagedObject) -> Bool {
23         if key != "api_plane_info" { return false }
24         
25         guard let airbase = object as? KCAirBase else {
26             print("object is not AirBase")
27             return false
28         }
29         if airbase.planeInfo.count == 0 {
30             let moc = airbase.managedObjectContext
31             let new: [KCAirBasePlaneInfo] = (0..<4).flatMap {_ in
32                 NSEntityDescription.insertNewObject(forEntityName: "AirBasePlaneInfo", into: moc!) as? KCAirBasePlaneInfo
33             }
34             airbase.planeInfo = NSOrderedSet(array: new)
35         }
36         
37         guard let planeInfos = value as? [[String: Any]]
38             else {
39                 print("value is wrong")
40                 return false
41         }
42         guard let infos = airbase.planeInfo.array as? [KCAirBasePlaneInfo]
43             else { print("airbase is wrong")
44                 return false
45         }
46         zip(infos, planeInfos).forEach { (info, dict) in
47             guard let slotid = dict["api_slotid"] as? Int,
48                 slotid != 0
49                 else { return }
50             guard let cond = dict["api_cond"] as? Int,
51                 let count = dict["api_count"] as? Int,
52                 let maxCount = dict["api_max_count"] as? Int,
53                 let squadronid = dict["api_squadron_id"] as? Int,
54                 let state = dict["api_state"] as? Int
55                 else { return print("planeInfos is wrong") }
56             info.cond = cond
57             info.count = count
58             info.max_count = maxCount
59             info.slotid = slotid
60             info.squadron_id = squadronid
61             info.state = state
62             info.airBase = airbase
63         }
64         return true
65     }
66 }