// Copyright (C) 2022 Marius Schellenberger

package fs

import (
	"context"
	"net/http"
	"os"

	"golang.org/x/net/webdav"
)

type WebDavFile struct {
	http.File
}

func (*WebDavFile) Write(_ []byte) (int, error) {
	return 0, os.ErrPermission
}

type WebDavFS struct {
	fs *FS
}

func NewWebDavFS(fs *FS) *WebDavFS {
	return &WebDavFS{fs}
}

func (*WebDavFS) Mkdir(_ context.Context, _ string, _ os.FileMode) error {
	return os.ErrPermission
}
func (*WebDavFS) RemoveAll(_ context.Context, _ string) error {
	return os.ErrPermission
}
func (*WebDavFS) Rename(_ context.Context, _, _ string) error {
	return os.ErrPermission
}

func (w *WebDavFS) OpenFile(_ context.Context, name string, flags int, _ os.FileMode) (webdav.File, error) {
	if flags&os.O_RDWR == os.O_RDWR ||
		flags&os.O_CREATE == os.O_CREATE ||
		flags&os.O_TRUNC == os.O_TRUNC {
		return nil, os.ErrPermission
	}
	f, err := w.fs.Open(name)
	if err != nil {
		return nil, err
	}
	return &WebDavFile{f}, err
}

func (w *WebDavFS) Stat(_ context.Context, name string) (os.FileInfo, error) {
	return w.fs.Stat(name)
}
