package main

import (
	"bytes"
	"errors"
	"image"
	"image/png"

	"github.com/liyue201/goqr"
	"github.com/skip2/go-qrcode"
)

// GenerateQRPNG returns PNG bytes for the given text.
func GenerateQRPNG(text string, size int) ([]byte, error) {
	if size <= 0 {
		size = 256
	}
	png, err := qrcode.Encode(text, qrcode.Medium, size)
	if err != nil {
		return nil, err
	}
	return png, nil
}

// DecodeQR decodes first QR code text from an image.
func DecodeQR(img image.Image) (string, error) {
	codes, err := goqr.Recognize(img)
	if err != nil {
		return "", err
	}
	if len(codes) == 0 {
		return "", errors.New("no qr code found")
	}
	return string(codes[0].Payload), nil
}

// LoadPNG decodes raw PNG bytes to image.Image.
func LoadPNG(b []byte) (image.Image, error) {
	im, err := png.Decode(bytes.NewReader(b))
	if err != nil {
		return nil, err
	}
	return im, nil
}
