package wow.doge.mygame.utils

import monix.reactive.Observable
import monix.reactive.OverflowStrategy
import monix.execution.Cancelable
import monix.execution.cancelables.SingleAssignCancelable
import monix.execution.Ack

object MonixDirectoryWatcher {
  import better.files._
  import io.methvin.better.files._
  def apply(path: os.Path) =
    Observable.create[String](OverflowStrategy.DropNew(50)) { sub =>
      import sub.scheduler

      val c = SingleAssignCancelable()

      val myDir = File(path.toString)
      val watcher = new RecursiveFileMonitor(myDir) {
        override def onCreate(file: File, count: Int) =
          println(s"$file got created")
        override def onModify(file: File, count: Int) =
          //   println(s"$file got modified $count times")
          if (sub.onNext(file.name) == Ack.Stop) c.cancel()
        override def onDelete(file: File, count: Int) =
          println(s"$file got deleted")
      }
      watcher.start()(scheduler)
      c := Cancelable(() => watcher.stop())
      c

    }
}
