// Copyright (C) 2022 Marius Schellenberger

package srv

import (
	"net/http"
	"strings"

	"cachefs/pkg/fs"

	"github.com/go-logr/logr"
	"golang.org/x/exp/slices"
	"golang.org/x/net/webdav"
)

type WebDavServer struct {
	log logr.Logger
	h   http.Handler
}

func NewWebDavServer(fs *fs.WebDavFS, log logr.Logger) http.Handler {
	return &WebDavServer{
		log,
		&webdav.Handler{
			FileSystem: fs,
			LockSystem: webdav.NewMemLS(),
		},
	}
}

func (dav *WebDavServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s := &statusInterceptor{w: w}
	if r.Method == http.MethodGet && !skipDavLog(r.RequestURI) {
		defer func() {
			if s.Status() == http.StatusPartialContent {
				return
			}
			dav.log.Info("access",
				"client", r.RemoteAddr,
				"method", r.Method,
				"status", s.Status(),
				"uri", r.RequestURI,
			)
		}()
	}
	dav.h.ServeHTTP(s, r)
}

var skipDavFiles = []string{
	"favicon.ico",
	"AlbumArtSmall.jpg",
	"AlbumArt.jpg",
	"Album.jpg",
	"cover.jpg",
	"cover.png",
	"cover.gif",
	"front.jpg",
	"front.png",
	"front.gif",
	"front.bmp",
	"thumb.jpg",
}

func skipDavLog(path string) bool {
	i := strings.LastIndex(path, "/")
	if i > 0 {
		path = path[i+1:]
	}
	return slices.Contains(skipDavFiles, path)
}
