OSDN Git Service

CoreDataのエンティティ名を文字列でアクセスしないようにした
[kcd/KCD.git] / KCD / MapStartCommand.swift
1 //
2 //  MapStartCommand.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/01/18.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 enum MapAPI: String {
12     case start = "/kcsapi/api_req_map/start"
13     case next = "/kcsapi/api_req_map/next"
14 }
15
16 class MapStartCommand: JSONCommand {
17     private let store = TemporaryDataStore.oneTimeEditor()
18     
19     override class func canExecuteAPI(_ api: String) -> Bool {
20         return MapAPI(rawValue: api) != nil ? true : false
21     }
22     
23     override func execute() {
24         MapAPI(rawValue: api).map {
25             switch $0 {
26             case .start: startBattle()
27             case .next:
28                 nextCell()
29                 updateBattleCell()
30             }
31         }
32         GuardShelterCommand(apiResponse: apiResponse).execute()
33     }
34     
35     private func startBattle() {
36         store.battles().forEach { store.delete($0) }
37         
38         guard let deckId = arguments["api_deck_id"].flatMap({ Int($0) }),
39             let mapArea = arguments["api_maparea_id"].flatMap({ Int($0) }),
40             let mapInfo = arguments["api_mapinfo_no"].flatMap({ Int($0) })
41             else { return print("startBattle Arguments is wrong") }
42         
43         guard let data = json["api_data"] as? [String: Any],
44             let no = data["api_no"] as? Int
45             else { return print("startBattle JSON is wrong") }
46         guard let battle = store.createBattle()
47             else { return print("Can not create Battle") }
48         battle.deckId = deckId
49         battle.mapArea = mapArea
50         battle.mapInfo = mapInfo
51         battle.no = no
52     }
53     private func nextCell() {
54         guard let data = json[dataKey] as? [String: Any],
55             let cellNumber = data["api_no"] as? Int,
56             let eventId = data["api_event_id"] as? Int
57             else { return print("updateBattleCell JSON is wrong") }
58         guard let battle = store.battle()
59             else { return print("Battle is invalid.") }
60         battle.no = cellNumber
61         battle.isBossCell = (eventId == 5)
62     }
63     private func updateBattleCell() {
64         store.battle().map { $0.battleCell = nil }
65     }
66 }