package main

import (
	"fmt"
	"strings"

	h "git.bullercodeworks.com/brian/adventofcode/helpers"
)

func main() {
	inp := h.StdinToStringSlice()
	dots := h.CoordByteMap{
		Field: make(map[h.Coordinate]byte),
	}
	var folds []h.Coordinate

	var inst bool
	for i := range inp {
		if inst {
			// folding instructions
			pts := strings.Split(inp[i], "=")
			v := h.Atoi(pts[1])
			if pts[0][len(pts[0])-1] == 'x' {
				folds = append(folds, h.Coordinate{X: v, Y: -1})
			} else {
				folds = append(folds, h.Coordinate{X: -1, Y: v})
			}
		} else if inp[i] == "" {
			inst = true
		} else {
			// A dot
			pts := strings.Split(inp[i], ",")
			c := h.Coordinate{X: h.Atoi(pts[0]), Y: h.Atoi(pts[1])}
			dots.Put(c, '#')
		}
	}
	fmt.Println("# Part 1")
	fmt.Println(len(doFolds(dots, []h.Coordinate{folds[0]}).Field))
	fmt.Println()
	fmt.Println("# Part 2")
	dots = doFolds(dots, folds)
	fmt.Println("Total Dots:", len(dots.Field))
	for y := 0; y < dots.Height; y++ {
		for x := 0; x < dots.Width; x++ {
			b := dots.Get(h.Coordinate{X: x, Y: y})
			if b != 0 {
				fmt.Print("▓")
			} else {
				fmt.Print(" ")
			}
		}
		fmt.Print("\n")
	}
}

func doFolds(dots h.CoordByteMap, folds []h.Coordinate) h.CoordByteMap {
	for i := range folds {
		newDots := h.CoordByteMap{
			Field: make(map[h.Coordinate]byte),
		}
		if folds[i].X != -1 {
			for k := range dots.Field {
				if k.X > folds[i].X {
					k.X = folds[i].X - (k.X - folds[i].X)
				}
				newDots.Put(k, '#')
			}
		} else if folds[i].Y != -1 {
			for k := range dots.Field {
				if k.Y > folds[i].Y {
					k.Y = folds[i].Y - (k.Y - folds[i].Y)
				}
				newDots.Put(k, '#')
			}
		}
		dots = newDots
	}
	return dots
}
