package domain

import (
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"io"
	"mime"
	"path"
	"time"

	_ "golang.org/x/image/bmp"
	_ "golang.org/x/image/webp"
)

type Resource struct {
	modTime      time.Time
	params       map[string]any
	File         Path
	mediaType    MediaType
	key          string
	name         string
	resourceType ResourceType
	title        string
	image        image.Config
}

func NewResource(modTime time.Time, r io.Reader, key string) *Resource {
	mediaType, _, _ := mime.ParseMediaType(mime.TypeByExtension(path.Ext(key)))
	out := &Resource{
		File:      NewPath(key),
		modTime:   modTime,
		key:       key,
		name:      key,                  // TODO(toby3d): set from Page configuration
		title:     "",                   // TODO(toby3d): set from Page configuration
		params:    make(map[string]any), // TODO(toby3d): set from Page configuration
		mediaType: NewMediaType(mediaType),
	}

	switch path.Ext(key) {
	default:
		out.resourceType = ResourceType(out.mediaType.mainType)
	case ".md":
		out.resourceType = ResourceTypePage
	case ".webmanifest":
		out.resourceType = ResourceTypeText
	}

	switch out.resourceType {
	case ResourceTypeImage:
		out.image, _, _ = image.DecodeConfig(r)
	}

	return out
}

func (r Resource) Key() string {
	return r.key
}

func (r Resource) Name() string {
	return r.name
}

func (r Resource) MediaType() MediaType {
	return r.mediaType
}

// Width returns width if current r is an image.
func (r Resource) Width() uint {
	return uint(r.image.Width)
}

// Height returns height if current r is an image.
func (r Resource) Height() uint {
	return uint(r.image.Height)
}

func (r Resource) ResourceType() ResourceType {
	return r.resourceType
}

func (f Resource) GoString() string {
	return "domain.Resource(" + f.key + ")"
}

// ResourceModTime used in http.ServeContent to get modtime of this resource.
func ResourceModTime(r *Resource) time.Time {
	if r == nil {
		return time.Time{}
	}

	return r.modTime
}
