aboutsummaryrefslogtreecommitdiff
path: root/Map/Logic/MapParser/Strategies/NoteParserStrategy.swift
blob: 4dae4c7aaed40f91d588c4b5b42514b2e75f3a83 (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
import Foundation

struct NoteParserStrategy: MapParserStrategy {
  private let regex = MapParsingPatterns.note

  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 == 5
  }

  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]
    let text = String(line[Range(match.range(at: 4), in: line)!])
    let xString = String(line[Range(match.range(at: 2), in: line)!])
    let yString = String(line[Range(match.range(at: 3), in: line)!])
    let x = CGFloat(truncating: NumberFormatter().number(from: xString) ?? 0.0)
    let y = CGFloat(truncating: NumberFormatter().number(from: yString) ?? 0.0)

    let note = Note(
      id: index,
      position: CGPoint(x: x, y: y),
      text: text
    )

    return (Note.self, note)
  }
}