package wow.doge.mygame

import scala.concurrent.duration._

import _root_.monix.bio.BIOApp
import _root_.monix.bio.Task
import _root_.monix.bio.UIO
import akka.util.Timeout
import cats.effect.ExitCode
import cats.effect.Resource
import cats.implicits._
import com.softwaremill.macwire._
import io.odin._
import io.odin.json.Formatter
import io.odin.syntax._
import scalafx.scene.control.TextArea
import wow.doge.mygame.game.GameAppResource
import wow.doge.mygame.utils.GenericConsoleStream

object Main extends BIOApp with MainModule {
  import java.util.logging.{Logger => JLogger, Level}
  JLogger.getLogger("").setLevel(Level.SEVERE)
  implicit val timeout = Timeout(1.second)

  def appResource(consoleStream: GenericConsoleStream[TextArea]) =
    for {
      logger <-
        consoleLogger().withAsync(
          timeWindow = 1.milliseconds,
          maxBufferSize = Some(2000)
        ) |+|
          fileLogger(
            "application-log-1.log",
            Formatter.json
          ).withAsync(timeWindow = 1.milliseconds, maxBufferSize = Some(2000))
      jmeScheduler <- jMESchedulerResource
      actorSystem <- actorSystemResource(logger)
      gameApp <- {
        // new BulletAppState()
        // bas.setThreadingType(Thr)
        // gameAppResource(new StatsAppState())
        wire[GameAppResource].get
      }
      _ <- Resource.liftF(
        new MainApp(
          logger,
          gameApp,
          actorSystem,
          jmeScheduler,
          schedulers,
          consoleStream
        )(
          timeout,
          actorSystem.scheduler
        ).program
      )

    } yield ()

  def run(args: List[String]): UIO[ExitCode] = {

    lazy val consoleStream = GenericConsoleStream.textAreaStream()
    Console.withOut(consoleStream)(
      appResource(consoleStream)
        .use(_ => Task.unit >> Task(consoleStream.close()))
        .onErrorHandle(_.printStackTrace())
        .as(ExitCode.Success)
    )
  }
}
