package wow.doge.mygame.subsystems.scriptsystem

import akka.actor.typed.ActorRef
import akka.actor.typed.Scheduler
import akka.actor.typed.SpawnProtocol
import akka.util.Timeout
import cats.effect.Resource
import monix.bio.Task
import wow.doge.mygame.scriptsystem.ScriptCachingActor
import wow.doge.mygame.utils.AkkaUtils

/**
  * Scripts can either be searched and compiled at startup (Eager mode)
  * or compiled on demand (Lazy mode)
  */
sealed trait ScriptInitMode
object ScriptInitMode {
  case object Eager extends ScriptInitMode
  case object Lazy extends ScriptInitMode
}
class ScriptSystemResource(
    path: os.Path,
    spawnProtocol: ActorRef[SpawnProtocol.Command],
    mode: ScriptInitMode = ScriptInitMode.Lazy
)(implicit timeout: Timeout, scheduler: Scheduler) {
  val make = {
    // throw new Exception("boom")
    findScriptFiles(os.pwd / "assets" / "scripts")

    lazy val scriptCacheActor = AkkaUtils.spawnActorL(
      spawnProtocol,
      "scriptCachingActor",
      ScriptCachingActor()
    )

    Resource.liftF(scriptCacheActor)
  }
  // sys.ask(ref => ScriptCachingActor.GetAll(os.pwd/'assets/'scripts/'scala/"hello2.sc",ref, false))

  val init = for {
    scriptFiles <- Task(findScriptFiles(os.pwd / "assets" / "scripts"))
    scriptCacheActor <- AkkaUtils.spawnActorL(
      spawnProtocol,
      "scriptCachingActor",
      ScriptCachingActor()
    )
  } yield (scriptCacheActor)

  def findScriptFiles(wd: os.Path) =
    os.walk
      .stream(wd)
      .filter(p =>
        os.isFile(p) &&
          (p.ext == "sc" || (p.baseName + "." + p.ext)
            .contains(".main.kts") || p.ext == "groovy")
      )
      .toList

  // def findExternalScriptFiles =
  //   findScriptFiles(os.pwd / "assets" / "scripts")
  // def findInternalScriptFiles =
  //   findScriptFiles((os.resource / "assets" / "scripts"))

  // def finalInternalScriptFiles =
}
// pwd / 'src / 'main / 'resources / 'assets / 'scripts
