package eu.xeppaka.scalalearn

import akka.actor.ActorSystem
import akka.stream.{ActorMaterializer, OverflowStrategy}
import akka.stream.scaladsl.{Sink, Source, Tcp}
import akka.util.ByteString

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn

object Main11 {
  def main(args: Array[String]): Unit = {
    val actorSystem = ActorSystem()
    val materializer = ActorMaterializer()(actorSystem)

    val queue = Source
      .queue[Int](0, OverflowStrategy.dropHead)
      .map(i => {
        println(s"before buffer elem: $i")
        i
      })
      .map(i => {
        println(s"after buffer elem: $i")
        i
      })
      .map(i => ByteString.fromString(s"$i"))
      .via(Tcp()(actorSystem).outgoingConnection("10.18.255.30", 9093))
      .to(Sink.foreach(println))
      .run()(materializer)

    try {
      println(Await.result(queue.offer(1), 2.seconds))
      println(Await.result(queue.offer(2), 2.seconds))
      println(Await.result(queue.offer(3), 2.seconds))

      println("before readline")

      StdIn.readLine()
    } finally {
      actorSystem.terminate()
    }
  }
}
