package thumbnail

import (
	"image"
	"mime"
	"path/filepath"
	"strings"
)

type DirectThumbnailer struct {
	cfg Config
}

var _ Thumbnailer = &DirectThumbnailer{} // interface assertion

func NewThumbnailer(w, h int) Thumbnailer {
	opts := DefaultConfig
	opts.Width = w
	opts.Height = h

	return NewThumbnailerEx(&opts)
}

func NewThumbnailerEx(opts *Config) Thumbnailer {
	if opts == nil {
		opts = &DefaultConfig
	}

	return &DirectThumbnailer{cfg: *opts}
}

func (this *DirectThumbnailer) RenderFile(absPath string) ([]byte, error) {
	mimeType := mime.TypeByExtension(filepath.Ext(absPath))
	return this.RenderFileAs(absPath, mimeType)
}

func (this *DirectThumbnailer) RenderFileAs(absPath, mimeType string) ([]byte, error) {

	// Decode source

	var src image.Image
	var err error = nil
	if strings.HasPrefix(mimeType, `image/`) {
		src, err = this.imageSnapshot(absPath, mimeType)

	} else if strings.HasPrefix(mimeType, `video/`) {
		src, err = this.videoSnapshot(absPath)

	} else {
		return nil, ErrUnsupportedFiletype

	}
	if err != nil {
		return nil, err
	}

	// Scale

	dest, err := this.scaleImage(src)
	if err != nil {
		return nil, err
	}

	// Rasterise result

	return this.encode(dest)
}
