package main

import (
	"encoding/csv"
	"image"
	"image/color"
	"image/png"
	"math"
	"os"

	imgutil "git.nkpl.cc/twocookedfaggots/imageutils/pkg"
)

func nearestHighSqrt(n int) int {
	if math.Mod(math.Sqrt(float64(n)), 1) == 0 {
		return n
	}
	return nearestHighSqrt(n + 1)
}

type showColors struct {
	color.Palette
}

func (s showColors) ColorModel() color.Model {
	return color.RGBAModel
}

func (s showColors) Bounds() image.Rectangle {
	n := nearestHighSqrt(len(s.Palette))
	return image.Rect(0, 0, n, n)
}

func (s showColors) At(x, y int) color.Color {
	n := nearestHighSqrt(len(s.Palette))
	return s.Palette[y*n+x]
}

func check(err error) {
	if err != nil {
		panic(err)
	}
}

func Must[T any](v T, err error) T {
	check(err)
	return v
}

func Map[S1 ~[]T1, S2 ~[]T2, T1, T2 any](s S1, f func(T1) T2) S2 {
	result := make(S2, len(s))
	for i := range s {
		result[i] = f(s[i])
	}
	return result
}

func main() {
	r := csv.NewReader(os.Stdin)
	r.TrailingComma = true
	colors, err := r.Read()
	check(err)
	palette := color.Palette(
		Map[[]string, color.Palette](colors,
			func(v string) color.Color {
				println(v + "cat-v")
				return Must(imgutil.ParseHexColor(v))
			},
		),
	)

	err = png.Encode(os.Stdout, showColors{palette})
	check(err)
}
