package main

import "core:fmt"
import "core:os"
import "core:strings"

import mcp "lib:minicactpot"
import console "lib:console"

read_flags :: proc(board: []int) {
	if len(os.args) > 1 {
		fmt.printf("%v\n", os.args)
		for num, i in strings.split(os.args[1], ",") {
			if i >= len(board) {
				break
			}
			board[i] = int(num[0]) - '0'
		}
	}
}

draw_board :: proc(con: ^console.Console, board: []int) {
	// vertical
	for y in 2 ..< 7 {
		left_char := '║' if (y - 1) % 2 != 0 else '╟'
		right_char := '║' if (y - 1) % 2 != 0 else '╢'
		con->putch(left_char, 1, y)
		con->putch(right_char, 13, y)

		con->putch('│', 5, y)
		con->putch('│', 9, y)
	}

	// horizontal
	for x in 2 ..< 13 {
		top_char := '═' if (x - 1) % 4 != 0 else '╤'
		bottom_char := '═' if (x - 1) % 4 != 0 else '╧'
		con->putch(top_char, x, 1)
		con->putch(bottom_char, x, 7)

		con->putch('─', x, 3)
		con->putch('─', x, 5)
	}

	// corners
	con->putch('╔', 0, 0)
	con->putch('╗', 13, 0)
	con->putch('╝', 13, 7)
	con->putch('╚', 0, 7)

	// center
	con->putch('┼', 5, 3)
	con->putch('┼', 9, 3)
	con->putch('┼', 9, 5)
	con->putch('┼', 5, 5)

	for v, i in board {
		// ((index % board_width) * width_step) + x_start_offset
		x := ((i % 3) * 4) + 3
		// ((index / board_width) * height_step) + y_start_offset
		y := (int(i / 3) * 2) + 2
		con->putch('0' + rune(v), x, y)
	}
}

draw_winning_pattern :: proc(con: ^console.Console, board: []int, pattern: []int) {
	for i in pattern {
		y := (int(i / 3) * 2) + 2
		x := ((i % 3) * 4) + 2
		con->write(fmt.tprintf(
			console.CURSOR_POSITION + console.CSI + "%d;%dm[%d]",
			y,
			x,
			console.BG_CYAN,
			console.FG_BLACK,
			board[i],
		))
	}
	con->write(console.RESET_FORMAT)
}

main :: proc() {
	board := [9]int{0, 0, 0, 0, 0, 0, 0, 0, 0}
	read_flags(board[:])

	con := console.create()
	defer con->destroy()

	con->clear()

	draw_board(&con, board[:])
	winning_pattern := mcp.solve(board[:])
	draw_winning_pattern(&con, board[:], winning_pattern[:])

	con->write(fmt.tprintf(console.CURSOR_POSITION, 8, 1))
}