package service

import (
        "net/http"
        "os"
        "path"
        "strings"

        "github.com/gin-gonic/gin"
)

func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
        fileserver := http.FileServer(fs)
        if urlPrefix != "" {
                fileserver = http.StripPrefix(urlPrefix, fileserver)
        }
        return func(c *gin.Context) {
                if fs.Exists(urlPrefix, c.Request.URL.Path) {
                        fileserver.ServeHTTP(c.Writer, c.Request)
                        c.Abort()
                }
        }
}

type ServeFileSystem interface {
        http.FileSystem
        Exists(prefix string, path string) bool
}

type LocalFileSystem struct {
        http.FileSystem
        root    string
        indexes bool
}

func (l *LocalFileSystem) Exists(prefix string, filepath string) bool {
        p := strings.TrimPrefix(filepath, prefix)
        if len(p) < len(filepath) {
                name := path.Join(l.root, p)
                stats, err := os.Stat(name)
                if err != nil {
                        return false
                }
                if !l.indexes && stats.IsDir() {
                        return false
                }
                return true
        }
        return false
}

func LocalFile(root string, indexes bool) *LocalFileSystem {
        return &LocalFileSystem{
                FileSystem: gin.Dir(root, indexes),
                root:       root,
                indexes:    indexes,
        }
}
