package day10

import (
	"adventofcode2022/utils"
	_ "fmt"
	"strings"
)

func Part1(input string) int {
	lines := strings.Split(input, "\n")
	cycle := 0
	strength := 0
	x := 1
	for _, line := range lines {
		cmd := strings.Split(line, " ")
		switch {
		case cmd[0] == "noop":
			strength,cycle = cycles_1(1, cycle, strength, x)
		case cmd[0] == "addx":
			strength, cycle = cycles_1(2, cycle, strength, x)
			x += utils.MustAtoi(cmd[1])
		}
	}
	return strength
}

func Part2(input string) string {
	lines := strings.Split(input, "\n")
	cycle := 0
	x := 1
	crt := [6][40]string{}
	for _, line := range lines {
		cmd := strings.Split(line, " ")
		switch {
		case cmd[0] == "noop":
			cycle = cycles_2(1, cycle, x, &crt)
		case cmd[0] == "addx":
			cycle = cycles_2(2, cycle, x, &crt)
			x += utils.MustAtoi(cmd[1])
		}
	}
	output := "\n"
	for i:=0;i<6;i++ {
		for j:=0;j<40;j++ {
			output = output + crt[i][j]
		}
		output = output + "\n"
	}
	
	return output
}

func cycles_1(num int, cycle int, strength int, x int) (int, int) {
	for i:=0;i<num;i++ {
		cycle++
		if cycle == 20 {
			strength = strength + (x * cycle)
		} else if  (cycle - 20) % 40 == 0 {
			strength = strength + (x * cycle)
		}
	}
	return strength, cycle
}

func cycles_2(num int, cycle int, x int, crt *[6][40]string) int {
	for i:=0;i<num;i++ {
		crt_x := cycle / 40
		crt_y := cycle % 40
		if x-1 == crt_y || x == crt_y || x+1 == crt_y {
			crt[crt_x][crt_y] = "#"
		} else {
			crt[crt_x][crt_y] = " "
		}
		cycle++
	}
	return cycle
}