1 // Copyright (C) 2024 Rubén Beltrán del Río
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see https://map.tranquil.systems.
17 struct OpportunityParserStrategy: MapParserStrategy {
18 private let regex = MapParsingPatterns.opportunity
20 func canHandle(line: String) -> Bool {
21 let range = NSRange(location: 0, length: line.utf16.count)
22 let matches = regex.matches(in: String(line), options: [], range: range)
23 return matches.count > 0 && matches[0].numberOfRanges == 5
26 func handle(index: Int, line: String, vertices: [String: Vertex]) -> (Any.Type, Any) {
27 let range = NSRange(location: 0, length: line.utf16.count)
28 let matches = regex.matches(in: String(line), options: [], range: range)
30 let match = matches[0]
31 let multiplier = CGFloat(
32 String(line[Range(match.range(at: 3), in: line)!]) == "-" ? -1.0 : 1.0)
33 let vertex = String(line[Range(match.range(at: 2), in: line)!])
34 let opportunityString = String(line[Range(match.range(at: 4), in: line)!])
35 let opportunity = CGFloat(
36 truncating: NumberFormatter().number(from: opportunityString) ?? 0.0)
38 if let origin = vertices[vertex] {
39 let destination = CGPoint(
40 x: origin.position.x + opportunity * multiplier, y: origin.position.y)
41 let opportunity = Opportunity(id: index, origin: origin.position, destination: destination)
42 return (Opportunity.self, opportunity)
45 return (NSObject.self, NSObject()) // No matching object