package day05

import (
	"fmt"
	"strings"

	"github.com/philhanna/stack"
)

func Part1(input string) (result string) {

	result = ""
	var stacks [9]stack.Stack[string]
	var lineNo int

	for i := 0; i < 9; i++ {
		stacks[i] = stack.NewStack[string]()
	}

	lines := strings.Split(input, "\n")
	for n, line := range lines {
		if line == " 1   2   3   4   5   6   7   8   9 " {
			lineNo = n + 2
			break
		}
		for i, r := range line {
			if r != ' ' && r != '[' && r != ']' {
				stacks[i/4].Push(string(r))
			}
		}
	}
	for i := 0; i < 9; i++ {
		stacks[i].Reverse()
	}
	var quantity, from, to int
	for _, line := range lines[lineNo:] {
		fmt.Sscanf(line, "move %d from %d to %d", &quantity, &from, &to)
		for i := 0; i < quantity; i++ {
			value, _ := (stacks[from-1]).Pop()
			stacks[to-1].Push(value)
		}
	}
	for i := 0; i < 9; i++ {
		item, _ := stacks[i].Peek()
		result = result + item
	}
	return
}

func Part2(input string) (result string) {

	result = ""
	var stacks [9]stack.Stack[string]
	tmp := stack.NewStack[string]()
	var lineNo int

	for i := 0; i < 9; i++ {
		stacks[i] = stack.NewStack[string]()
	}

	lines := strings.Split(input, "\n")
	for n, line := range lines {
		if line == " 1   2   3   4   5   6   7   8   9 " {
			lineNo = n + 2
			break
		}
		for i, r := range line {
			if r != ' ' && r != '[' && r != ']' {
				stacks[i/4].Push(string(r))
			}
		}
	}
	for i := 0; i < 9; i++ {
		stacks[i].Reverse()
	}
	var quantity, from, to int
	for _, line := range lines[lineNo:] {
		fmt.Sscanf(line, "move %d from %d to %d", &quantity, &from, &to)
		for i := 0; i < quantity; i++ {
			value, _ := (stacks[from-1]).Pop()
			tmp.Push(value)
		}
		for i := 0; i < quantity; i++ {
			value, _ := tmp.Pop()
			stacks[to-1].Push(value)
		}
	}
	for i := 0; i < 9; i++ {
		item, _ := stacks[i].Peek()
		result = result + item
	}
	return
}
