package readutil

import (
	"compress/bzip2"
	"compress/gzip"
	"errors"
	"io"

	"github.com/andybalholm/brotli"
	xz "github.com/remyoudompheng/go-liblzma"
	"sour.is/x/toolbox/log"
)

// Decompress varius types of compression types
func Decompress(in io.Reader) (io.Reader, error) {
	rdr := NewPreviewReader(in)
	mime, err := ReadMIMEWithSize(rdr, "", 32768)
	if err != nil {
		return rdr.Drain(), err
	}
	r := rdr.Drain()

	switch mime {
	case "application/gzip":
		r, err = gzip.NewReader(r)

	case "application/x-bzip2":
		r = bzip2.NewReader(r)

	case "application/x-xz":
		r, err = xz.NewReader(r)

	case "application/brotli":
		r = brotli.NewReader(r)
	default:
		return r, ErrUnsupportedType
	}
	log.Debugs("Decompress:", "mime", mime)

	return r, err
}

var ErrUnsupportedType = errors.New("Unsupported decompression type")
