package main

import (
	"AOC2021/src/helper"
	"fmt"
	"os"
)

type field struct {
	energy  int
	flashed bool
}

func main() {
	args := os.Args[1:]
	input, err := helper.GetInput(args[0])
	if err != nil {
		fmt.Println(err)
	}
	energyMap := [10][10]field{}
	for i, line := range input {
		for j, r := range line {
			energyMap[i][j] = field{int(r - '0'), false}
		}
	}
	flashes := 0
	allFlashTogether := false
	i := 0
	for !allFlashTogether {
		stepflashes := step(&energyMap)
		flashes += stepflashes
		if stepflashes == 100 {
			fmt.Printf("First Step, where all octuspuses flash simultaneously: %d \n", i + 1)
			allFlashTogether = true
		}
		if i == 99 {
			fmt.Printf("Flashes after 100 Steps: %d \n", flashes)
		}
		i++
	}
}

func step(energyMap *[10][10]field) int{
	flashes := 0
	for i, _ := range energyMap {
		for j, _ := range energyMap[i] {
			energyMap[i][j].energy++
		}
	}
	for i, _ := range energyMap {
		for j, _ := range energyMap[i] {
			if energyMap[i][j].energy > 9 {
				flash(energyMap, j, i)
			}
		}
	}
	for i, _ := range energyMap {
		for j, _ := range energyMap[i] {
			if energyMap[i][j].flashed {
				energyMap[i][j].energy = 0
				flashes++
				energyMap[i][j].flashed = false
			}
		}
	}
	return flashes
}

func flash(energyMap *[10][10]field, x int, y int) {
	if energyMap[y][x].flashed == true {
		return
	}
	energyMap[y][x].flashed = true
	directions := [8][2]int{{-1, -1}, {0, -1}, {1, -1}, {+1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}}
	for _, direction := range directions {
		px := x + direction[0]
		py := y + direction[1]
		if py < len(energyMap) && py >= 0 && px < len(energyMap[0]) && px >= 0 {
			energyMap[py][px].energy++
			if energyMap[py][px].energy > 9 {
				flash(energyMap, px, py)
			}
		}
	}
}
