package ui

import (
	"io"
	"os"

	"opslag.de/schobers/zntg"
)

var _ Resources = &CopyResources{}

// CopyResources copies and opens resources to a temporary directory.
type CopyResources struct {
	Source Resources

	copy *zntg.Dir
}

// NewCopyResource creates a proxy that copied resources first to disk.
func NewCopyResource(prefix string, source Resources) (*CopyResources, error) {
	copy, err := zntg.NewTempDir(prefix)
	if nil != err {
		return nil, err
	}
	return &CopyResources{source, copy}, nil
}

// FetchResource copies the file from the source to disk and returns the path to it.
func (r *CopyResources) FetchResource(name string) (string, error) {
	path := r.copy.FilePath(name)
	if !zntg.FileExists(path) {
		src, err := r.Source.OpenResource(name)
		if err != nil {
			return "", err
		}
		defer src.Close()

		err = r.copy.Write(name, src)
		if nil != err {
			return "", err
		}
	}
	return path, nil
}

// OpenResource opens the (copied) resource on disk.
func (r *CopyResources) OpenResource(name string) (io.ReadCloser, error) {
	path := r.copy.FilePath(name)
	src, err := os.Open(path)
	return src, err
}

// Destroy destroy the copy of the resources.
func (r *CopyResources) Destroy() error {
	return r.copy.Destroy()
}