import type { Plugin } from 'vite'
import fs from 'fs'

export function fileWatcher(...options: VitePluginTypes.FileWatcherOptions[]): Plugin {
  return {
    name: 'file-watcher-plugin',

    configureServer(server) {
      server.watcher
        .on('all', (event, filePath, stats) => {
          options.forEach(it => {
            const isDir = stats!.isDirectory()
            const getContent = () => {
              return isDir ? '' : fs.readFileSync(filePath, 'utf-8')
            }
            const isAccept = it.isAccept({event, filePath, isDir})
            if (isAccept) {
              it.process({
                event, filePath, isDir, getContent,
              })
            }
          })
        })
    },
  }
}
