package eu.xeppaka.scalalearn

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.stream.{ActorMaterializer, Materializer}
import akka.stream.scaladsl.{Keep, Sink, Source}
import akka.util.Timeout
import eu.xeppaka.scalalearn.Actor1.{FinishFailure, FinishSuccess, Print, Start}
import eu.xeppaka.scalalearn.Actor2._

import scala.concurrent.duration._
import scala.util.{Failure, Success}

object Actor1 {
  case object Start
  case object FinishSuccess
  case object FinishFailure
  case object Print

  def props(actor2: ActorRef): Props = Props(new Actor1(actor2))
}

class Actor1(actor2: ActorRef) extends Actor with ActorLogging {
  import context.dispatcher

  implicit val timeout: Timeout = 2.seconds
  implicit val materializer: Materializer = ActorMaterializer()

  override def receive: Receive = {
    case Start =>
      Source
        .repeat(Request)
        .take(100)
        .ask[Response.type](actor2)
        .toMat(Sink.foreach(response => log.info(response.toString)))(Keep.right)
        .run()
        .onComplete {
          case Success(_) => self ! FinishSuccess
          case Failure(_) => self ! FinishFailure
        }
    case FinishSuccess =>
      log.info("actor1 finish success")
    case FinishFailure =>
      log.info("actor1 finish failure")
    case Print =>
      log.info("print done")
  }
}
