package wow.doge.mygame

import scala.concurrent.duration._

import _root_.monix.bio.BIOApp
import _root_.monix.bio.Task
import _root_.monix.bio.UIO
import _root_.monix.execution.Scheduler
import akka.util.Timeout
import cats.effect.ExitCode
import cats.effect.Resource
import cats.implicits._
import io.odin._
import io.odin.json.Formatter
import io.odin.syntax._
import scalafx.scene.control.TextArea
import wow.doge.mygame.ActorSystemResource
import wow.doge.mygame.executors.ExecutorsModule
import wow.doge.mygame.types.AkkaScheduler
import wow.doge.mygame.utils.GenericConsoleStream
object Main extends BIOApp with ExecutorsModule {
  import java.util.logging.{Logger => JLogger, Level}
  JLogger.getLogger("").setLevel(Level.SEVERE)
  implicit val timeout = Timeout(1.second)

  override def scheduler: Scheduler = schedulers.async.value

  def appResource(consoleStream: GenericConsoleStream[TextArea]) =
    for {
      logger <-
        consoleLogger().withAsync(
          timeWindow = 1.milliseconds,
          maxBufferSize = Some(100)
        ) |+|
          fileLogger(
            "application-log-1.log",
            Formatter.json
          ).withAsync(timeWindow = 1.milliseconds, maxBufferSize = Some(2000))
      jmeScheduler <- jmeSchedulerResource
      // backend <- Resource.make(toIO(HttpClientMonixBackend()))(backend =>
      //   toIO(backend.close())
      // )
      actorSystem <- new ActorSystemResource(logger, schedulers.async).get
      _ <- Resource.liftF(
        new MainApp(
          logger,
          jmeScheduler,
          schedulers,
          consoleStream
        )(actorSystem, timeout, AkkaScheduler(actorSystem.scheduler)).program
      )

    } yield ()

  def run(args: List[String]): UIO[ExitCode] = {
    val consoleStream = GenericConsoleStream.textAreaStream()
    Console.withOut(consoleStream)(
      appResource(consoleStream)
        .use(_ => Task.unit)
        .flatMap(_ => Task(consoleStream.close()))
        .onErrorHandleWith(ex => UIO(ex.printStackTrace()))
        .as(ExitCode.Success)
    )
  }
}
