// aoc (12/1/21)
// © 2021 Joe Sherwood. All rights reserved.

extension AOC21 {
  
  public class Day02: Day {
    public convenience init() { self.init(source: .file(#file)) }

    public override func p1() -> String {
      var horizontal = 0
      var vertical = 0
      
      let instructions = self.input.lines
      for instruction in instructions {
        if (instruction.data ~= "^forward (\\d+)$") {
          let regex = Regex(pattern: "^forward (\\d+)$")
          let captures = regex.captureGroups(instruction.data)
          let magnitude = Int(captures[0]) ?? 0
          horizontal += magnitude
        }
        else if (instruction.data ~= "^down (\\d+)$") {
          let regex = Regex(pattern: "^down (\\d+)$")
          let captures = regex.captureGroups(instruction.data)
          let magnitude = Int(captures[0]) ?? 0
          vertical += magnitude
        }
        else if (instruction.data ~= "^up (\\d+)$") {
          let regex = Regex(pattern: "^up (\\d+)$")
          let captures = regex.captureGroups(instruction.data)
          let magnitude = Int(captures[0]) ?? 0
          vertical -= magnitude
        }
      }
      
      return "\(horizontal * vertical)"
    }
    
    public override func p2() -> String {
      var horizontal = 0
      var vertical = 0
      var aim = 0
      
      let instructions = self.input.lines
      for instruction in instructions {
        if (instruction.data ~= "^forward (\\d+)$") {
          let regex = Regex(pattern: "^forward (\\d+)$")
          let captures = regex.captureGroups(instruction.data)
          let magnitude = Int(captures[0]) ?? 0
          horizontal += magnitude
          vertical += magnitude * aim
        }
        else if (instruction.data ~= "^down (\\d+)$") {
          let regex = Regex(pattern: "^down (\\d+)$")
          let captures = regex.captureGroups(instruction.data)
          let magnitude = Int(captures[0]) ?? 0
          aim += magnitude
        }
        else if (instruction.data ~= "^up (\\d+)$") {
          let regex = Regex(pattern: "^up (\\d+)$")
          let captures = regex.captureGroups(instruction.data)
          let magnitude = Int(captures[0]) ?? 0
          aim -= magnitude
        }
      }
      
      return "\(horizontal * vertical)"
    }
  }
  
}
