package util

import (
	"errors"
	"fmt"
	"image/color"
)

var ParseHexColorErr = errors.New("invalid length, must be 7 or 4")

func ParseHexColor(s string) (c color.RGBA, err error) {
	c.A = 0xff
	switch len(s) {
	case 7:
		_, err = fmt.Sscanf(s, "#%02x%02x%02x", &c.R, &c.G, &c.B)
	case 4:
		_, err = fmt.Sscanf(s, "#%1x%1x%1x", &c.R, &c.G, &c.B)
		// Double the hex digits:
		c.R *= 17
		c.G *= 17
		c.B *= 17
	default:
		err = ParseHexColorErr

	}
	return
}

func ColorToHex(c color.Color) string {
	r, g, b, _ := color.NRGBAModel.Convert(c).RGBA()
	return fmt.Sprintf("#%02x%02x%02x", byte(r), byte(g), byte(b))
}
