package eu.xeppaka.scalalearn

import java.util.concurrent.ConcurrentHashMap

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Sink, Source}

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

object Main1 {
  val mapsCount = 10000

  def mapKey(idCard: String) = s"map-${math.abs(idCard.hashCode) % mapsCount}"

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

    val resultMap = new ConcurrentHashMap[String, Int]()
    val l = 1 to 200000

    Source
      .fromIterator(() => l.iterator)
      .map(i => f"$i%032d")
      .groupBy(mapsCount, idCard => mapKey(idCard))
      .groupedWithin(100, 2.seconds)
      .mergeSubstreams
      .to(Sink.foreach(elems => elems.foreach(elem => resultMap.compute(mapKey(elem), (_, num) => num + 1))))
      .run()

    StdIn.readLine()

    resultMap.entrySet().asScala.foreach(pair => if (pair.getValue >= 25) println(pair))

    Await.ready(actorSystem.terminate(), 3.seconds)
  }
}
