package main

import (
	"fmt"

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

func main() {
	inp := h.StdinToStringSlice()

	seats := make(map[int]Seat)
	var topSeat int
	for k := range inp {
		row, col, seat := findSeatFromId(inp[k])
		seats[seat] = Seat{
			Row:  row,
			Col:  col,
			Seat: seat,
		}
		if seat > topSeat {
			topSeat = seat
		}
	}
	fmt.Println("# Part 1 - Top Seat:", topSeat)
	for k := range seats {
		_, tOk := seats[k-1]
		if !tOk {
			_, bOk := seats[k-2]
			if bOk {
				fmt.Println("# Part 2 - Missing Seat:", k-1)
				break
			}
		}
	}
}

type Seat struct {
	Row  int
	Col  int
	Seat int
}

func findSeatFromId(id string) (int, int, int) {
	rowBeg := 0
	rowEnd := 127
	colBeg := 0
	colEnd := 7
	for k := range id {
		switch id[k] {
		case 'F', 'B':
			rowBeg, rowEnd = findChunk(rowBeg, rowEnd, id[k] == 'F')
		case 'R', 'L':
			colBeg, colEnd = findChunk(colBeg, colEnd, id[k] == 'L')
		}
	}

	return rowBeg, colBeg, (rowBeg * 8) + colBeg
}

func findChunk(beg, end int, front bool) (int, int) {
	if beg == end {
		return beg, beg
	}
	if front {
		return beg, beg + (end-beg)/2
	} else {
		return beg + (end-beg)/2 + 1, end
	}
}
