aboutsummaryrefslogtreecommitdiff
path: root/Map/Logic/MapParser/Strategies/GroupParserStrategy.swift
blob: 79249353fedc40c5a4b3fe140e22213b5be7aa7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import Foundation

struct GroupParserStrategy: MapParserStrategy {
  private let regex = MapParsingPatterns.group

  func canHandle(line: String) -> Bool {
    let range = NSRange(location: 0, length: line.utf16.count)
    let matches = regex.matches(in: String(line), options: [], range: range)
    return matches.count > 0 && matches[0].numberOfRanges == 3
  }

  func handle(index: Int, line: String, vertices: [String: Vertex]) -> (Any.Type, Any) {
    let range = NSRange(location: 0, length: line.utf16.count)
    let matches = regex.matches(in: String(line), options: [], range: range)

    let match = matches[0]
    var groupVertices: [Vertex] = []
    let vertexIdString = String(line[Range(match.range(at: 2), in: line)!])
    let vertexIds = vertexIdString.split(separator: " ", omittingEmptySubsequences: true).map(
      String.init)

    for vertexId in vertexIds {
      if let vertex = vertices[vertexId] {
        groupVertices.append(vertex)
      }
    }

    if groupVertices.count > 0 {
      return ([Vertex].self, groupVertices)
    }

    return (NSObject.self, NSObject())
  }
}