// Copyright (C) 2022 Marius Schellenberger

package filter

import (
	"cachefs/pkg/provider"
	"io/fs"
	"path/filepath"
)

var _ provider.File = (*file)(nil)

type file struct {
	provider.File
	fs   *FS
	path string
}

func newFile(f provider.File, fs *FS, path string) (nf provider.File, err error) {
	nf = &file{
		File: f,
		fs:   fs,
		path: path,
	}
	return nf, nil
}

func (f *file) Readdir(n int) ([]fs.FileInfo, error) {
	fis, err := f.File.Readdir(n)
	if err != nil {
		return nil, err
	}
	fio := make([]fs.FileInfo, len(fis))
	i := 0
	for _, fi := range fis {
		file := filepath.Join(f.path, fi.Name())
		if f.fs.match(file) == nil {
			fio[i] = fi
			i++
		}
	}
	return fio[:i], nil
}

func (f *file) ReadDir(n int) ([]fs.DirEntry, error) {
	fis, err := f.Readdir(n)
	if err != nil {
		return nil, err
	}
	fio := make([]fs.DirEntry, len(fis))
	for i, fi := range fis {
		fio[i] = fs.FileInfoToDirEntry(fi)
	}
	return fio, nil
}
