package ru.yandex.atom.application

import akka.util.Timeout
import akka.io.IO
import scala.util.{Failure, Success}
import spray.can.Http
import akka.pattern.ask
import org.slf4j.LoggerFactory
import concurrent.duration._
import language.postfixOps
import akka.actor.ActorSystem
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * @author avhaliullin
 */
abstract class SprayApplication extends TypesafeApplication {
  self: HttpRouterComponent =>
  def actorSystem: ActorSystem

  override def postInit() {
    super.postInit()
    val log = LoggerFactory.getLogger(classOf[SprayApplication])

    implicit val timeout = Timeout(5 seconds)
    implicit val actorSystem = this.actorSystem

    val interface = "0.0.0.0"
    val port = getApplicationResources.getPort

    IO(Http).ask(Http.Bind(httpRouter, interface, port)
    ).mapTo[Http.Event].onComplete {
      case Success(Http.Bound(address)) =>
        log.info(s"Started on $address")
      case Success(Http.CommandFailed(_)) =>
        log.error(
          s"Couldn't start on $interface:$port - command failed")
        System.exit(1)
      case Failure(e) =>
        log.error(
          s"Couldn't start on $interface:$port", e)
        System.exit(1)
      case msg =>
        log.error(s"Unexpected answer from IO: $msg")
        System.exit(1)
    }
  }

}
