package images

import (
	"bytes"
	"compress/flate"
	"encoding/base64"
	"fmt"
	"io"
	"strings"
)

const (
	sourceSetSteps = 300
	sourceSetMax   = 1500
)

func UIDFromPath(path string) (uid string, err error) {
	var b bytes.Buffer
	// NewWriter with NoDict (nil) creates a raw DEFLATE compressor
	zw, _ := flate.NewWriter(&b, flate.BestCompression)

	_, err = zw.Write([]byte(path))
	if err != nil {
		return
	}
	err = zw.Close() // Essential to flush the final bits
	if err != nil {
		return
	}

	return base64.RawURLEncoding.EncodeToString(b.Bytes()), nil
}

func URLFromPath(path string) (url string, err error) {
	uid, err := UIDFromPath(path)
	url = "/images/" + uid
	return
}

func PathFromUID(uid string) (string, error) {
	// 1. Decode the Base64 string back to compressed bytes
	compressedBytes, err := base64.RawURLEncoding.DecodeString(uid)
	if err != nil {
		return "", err
	}

	// 2. Create a flate reader (NoDict/nil since you used nil in the writer)
	// flate.NewReader returns an io.ReadCloser
	reader := flate.NewReader(bytes.NewReader(compressedBytes))
	defer reader.Close()

	// 3. Read the decompressed data into a buffer
	var out bytes.Buffer
	_, err = io.Copy(&out, reader)
	if err != nil {
		return "", err
	}

	return out.String(), nil
}

func SourceSet(src string) string {
	sb := strings.Builder{}

	i := 1
	for {
		width := i * sourceSetSteps
		sb.WriteString(fmt.Sprintf("%s?w=%d %dw, ", src, width, width))
		if width >= sourceSetMax {
			return sb.String()
		}
		sb.WriteRune(',')
		i++
	}
}
