const chokidar = require('chokidar')
const fs = require('fs')

let emitComponent = (name, path) => {
  return `module ${name} = {
  @module("../svg/${path}") @react.component
  external make: (
    ~width: int=?,
    ~height: int=?,
    ~fill: string=?,
    ~stroke: string=?,
    ~className: string=?,
  ) => React.element = "default"
}
`
}

const rebuild = (watched) => {
  let components = []

  Object.entries(watched).forEach(([key, files]) => {
    let namePrefix = key == '.' ? '' : `${key}__`
    let pathPrefix = key == '.' ? '' : `${key}/`

    files.forEach((fileName) => {
      if (fileName.includes('.svg')) {
        let [name] = fileName.split('.')
        components.push(emitComponent(namePrefix + name, pathPrefix + fileName))
      }
    })
  })

  fs.writeFileSync('./components/Icon3.res', components.sort().join('\n'))
}

const watcher = chokidar.watch('.', { ignoreInitial: true, cwd: './svg' })

watcher
  .on('add', () => rebuild(watcher.getWatched()))
  .on('unlink', () => rebuild(watcher.getWatched()))
  .on('ready', () => rebuild(watcher.getWatched()))
