package com.example;

import akka.actor.typed.ActorRef;
import akka.actor.typed.Behavior;
import akka.actor.typed.javadsl.*;


// #greeter
public class Greeter extends AbstractBehavior<Greeter.Message> {

  public interface Message {}
  public record Response(boolean are_messages_left, Greet msg) implements Message {}
  public record Greet(String whom, ActorRef<Greeter.Greeted> replyTo) implements Message {}
  public record Greeted(String whom, ActorRef<Greeter.Message> replyTo) {}

  public static Behavior<Message> create(ActorRef<Overseer.Request> overseer) {
    return Behaviors.setup(context -> new Greeter(context, overseer));
  }

  private final ActorRef<Overseer.Request> overseer;
  private Greeter(ActorContext<Message> context, ActorRef<Overseer.Request> overseer) {
    super(context);
    this.overseer = overseer;
  }

  @Override
  public Receive<Message> createReceive() {
    return newReceiveBuilder().onMessage(Greet.class, this::onGreet).onMessage(Response.class, this::onResponse).build();
  }
  private Behavior<Message> onResponse(Response command) {
    if (command.are_messages_left()) {
      getContext().getLog().info("Hello {}!", command.msg().whom());
      //#greeter-send-message
      command.msg().replyTo().tell(new Greeter.Greeted(command.msg().whom(), getContext().getSelf()));
      //#greeter-send-message
    }
    return this;
  }

  private Behavior<Message> onGreet(Greet command) {
    overseer.tell(new Overseer.Request(command, getContext().getSelf()));
    return this;
  }
}
// #greeter

