//go:build !windows

package cell_size

import (
	"fmt"
	"os"
	"syscall"
	"unsafe"
)

type winsize struct {
	Rows    uint16
	Cols    uint16
	Xpixels uint16
	Ypixels uint16
}

func GetTerminalCellSizePixels() (widthPx int, heightPx int, err error) {
	ws := &winsize{}
	_, _, errno := syscall.Syscall(
		syscall.SYS_IOCTL,
		os.Stdout.Fd(),
		uintptr(syscall.TIOCGWINSZ),
		uintptr(unsafe.Pointer(ws)),
	)
	if errno != 0 {
		return 0, 0, errno
	}
	if ws.Cols == 0 || ws.Rows == 0 {
		return 0, 0, fmt.Errorf("terminal rows or columns is zero")
	}
	widthPx = int(ws.Xpixels) / int(ws.Cols)
	heightPx = int(ws.Ypixels) / int(ws.Rows)
	return
}

func GetConsoleSize() (int, int) {
	var sz struct {
		rows    uint16
		cols    uint16
		xpixels uint16
		ypixels uint16
	}
	_, _, _ = syscall.Syscall(syscall.SYS_IOCTL,
		uintptr(syscall.Stdout), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&sz)))
	return int(sz.cols), int(sz.rows)
}
