package day04

import (
	"adventofcode2024/utils/grid2d"
	"adventofcode2024/utils/inputs"
)

func Part1(input string) int {
	val := 0
	grid := inputs.ToGrid2D(input, "\n", "", '.', func(c string) rune { return rune(c[0])})
	directions := [][]int{{0,1},{0,-1},{1,0},{-1,0},{-1,1},{1,1},{-1,-1},{1,-1}}
	for j := 0; j < grid.SizeY(); j++ {
		for i := 0; i < grid.SizeX(); i++ {
			if  !checkChar(i, j, grid, 'X') { continue }			
			for _, dir := range directions {
				x := i + dir[0]
				y := j + dir[1]
				if !checkChar(x, y, grid, 'M') { continue }
				x = x + dir[0]
				y = y + dir[1]				
				if !checkChar(x, y, grid, 'A') { continue }
				x = x + dir[0]
				y = y + dir[1]				
				if !checkChar(x, y, grid, 'S') { continue }
				val++
			}
		}
	}
	return val
}

func Part2(input string) int {
	val := 0
	grid := inputs.ToGrid2D(input, "\n", "", '.', func(c string) rune { return rune(c[0])})
	dir1 := [][]int{{-1,1},{1,-1},}
	dir2 := [][]int{{1,1},{-1,-1}}
	for j := 0; j < grid.SizeY(); j++ {
		for i := 0; i < grid.SizeX(); i++ {
			if !checkChar(i, j, grid, 'A') { continue }
			if 
			(checkChar(i + dir1[0][0], j + dir1[0][1], grid, 'M') && checkChar(i + dir1[1][0], j +  dir1[1][1], grid, 'S') ||
			checkChar(i + dir1[0][0], j +  dir1[0][1], grid, 'S') && checkChar(i + dir1[1][0], j +  dir1[1][1], grid, 'M')) &&
			(checkChar(i + dir2[0][0], j + dir2[0][1], grid, 'M') && checkChar(i + dir2[1][0], j +  dir2[1][1], grid, 'S') ||
			checkChar(i + dir2[0][0], j +  dir2[0][1], grid, 'S') && checkChar(i + dir2[1][0], j +  dir2[1][1], grid, 'M') ) {
				val++ 
			}
		}
	}
	return val}

func checkChar(x int, y int, grid *grid2d.Grid[rune], c rune) bool {
	if x < 0 || x >= grid.SizeX() || y < 0 || y >= grid.SizeY() {
		return false
	}
	if grid.Get(x, y) == c {
		return true
	}
	return false
}