package ru.yandex.atom.db.cassandra

import akka.actor.{Props, Actor}
import scala.util.{Failure, Success}

/**
 * Обертка над future-api к кассандре.
 * @author avhaliullin
 */
trait CassandraActorComponentImpl extends CassandraActorComponent {
  component: CassandraComponent =>

  import CassandraRequest._
  import CassandraResponse._

  class CassandraActor extends Actor {

    implicit val executor = context.dispatcher

    def receive = {
      case req@ReadRequest(id, statement) =>
        val client = sender
        cassandra.execute(statement).onComplete {
          case Success(rows) =>
            client ! ReadResponse(req, rows)
          case Failure(err) =>
            client ! FailureResponse(req, err)
        }
      case req@WriteRequest(id, statement) =>
        val client = sender
        cassandra.update(statement).onComplete {
          case Success(_) =>
            client ! WriteResponse(req)
          case Failure(err) =>
            client ! FailureResponse(req, err)
        }
    }
  }

  object CassandraActor {
    def props = Props(classOf[CassandraActor], component)
  }

}
