package main

import (
	"AoC2020/helper"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	args := os.Args[1:]
	input, err := helper.GetInput(args[0])
	if err != nil {
		fmt.Println(err)
	}
	part1(input)
	part2(input)
}

func checkCorrect(time int, bustimes []int) bool {
	p := 0
	fmt.Print(bustimes)
	for _, bustime := range bustimes {
		if time%bustime > p {
			return false
		}
		p = time % bustime
	}
	return true
}

func part2(input []string) {
	busses := strings.Split(input[1], ",")
	var busTimes []int
	for _, val := range busses {
		if val != "x" {
			busTime, _ := strconv.Atoi(val)
			busTimes = append(busTimes, busTime)
		} else {
			busTimes = append(busTimes, 0)
		}
	}
	step := busTimes[0]
	time := 0
	for i, val := range busTimes[1:] {
		if val != 0 {
			fmt.Printf("Value: %d Step: %d \n",val,step)
			for (time+i+1)%val != 0 {
				time += step
			}
			step = step * val
		}
	}
	fmt.Println(time)
}

func part1(input []string) {
	arrival, _ := strconv.Atoi(input[0])
	busses := strings.Split(input[1], ",")
	minWaitTime := 999
	choosenBus := 0
	for _, val := range busses {
		if val != "x" {
			busTime, _ := strconv.Atoi(val)
			diff := arrival / busTime
			waitTime := busTime*(diff+1) - arrival
			if minWaitTime > waitTime {
				minWaitTime = waitTime
				choosenBus = busTime
			}
		}
	}
	fmt.Println(minWaitTime*choosenBus)
}

func timestampToMinutes(timeStamp string) int {
	hours := int(timeStamp[0] - '0')
	minutes, _ := strconv.Atoi(string(timeStamp[1:]))
	return hours*60 + minutes
}
