package resize_image

import (
	"image"
	"image/color"
	"whspbrd/pkg/cell_size"
)

func Resize(img image.RGBA, width int, height int) (*image.RGBA, error) {
	originalWidth := img.Bounds().Dx()
	originalHeight := img.Bounds().Dy()

	if width <= 0 && height <= 0 {
		return nil, nil
	} else if width <= 0 {
		width = int(float64(height) * float64(originalWidth) / float64(originalHeight))
	} else if height <= 0 {
		height = int(float64(width) * float64(originalHeight) / float64(originalWidth))
	}

	newImg := image.NewRGBA(image.Rect(0, 0, width, height))
	scaleX := float64(originalWidth) / float64(width)
	scaleY := float64(originalHeight) / float64(height)

	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			srcX := int(float64(x) * scaleX)
			srcY := int(float64(y) * scaleY)

			r, g, b, a := getPixel(img, srcX, srcY)
			newImg.Set(x, y, color.RGBA{r, g, b, a})
		}
	}

	return newImg, nil
}

func ResizeInTerminal(img image.RGBA, columns int, rows int) (*image.RGBA, error) {
	if columns <= 0 && rows <= 0 {
		return nil, nil
	}

	width := convertColumnsToPixels(columns)
	height := convertRowsToPixels(rows)

	return Resize(img, width, height)
}

func getPixel(img image.RGBA, x int, y int) (uint8, uint8, uint8, uint8) {
	index := img.PixOffset(x, y)
	return img.Pix[index], img.Pix[index+1], img.Pix[index+2], img.Pix[index+3]
}

func convertColumnsToPixels(columns int) int {
	w, _, err := cell_size.GetTerminalCellSizePixels()
	if err != nil {
		w = 8
	}
	return columns * w
}

func convertRowsToPixels(rows int) int {
	_, h, err := cell_size.GetTerminalCellSizePixels()
	if err != nil {
		h = 16
	}
	return rows * h
}
