package Zookeeper;

import Coordinator_Worker.Worker;
import org.apache.zookeeper.KeeperException;
import grpc.server.grpcServer;
public class OnElectionAction implements OnElectionCallback {


    private final ServiceRegistry serviceRegistry;
    private final int port;

    public OnElectionAction(ServiceRegistry serviceRegistry, int port) {
        this.serviceRegistry = serviceRegistry;
        this.port = port;
    }

    @Override
    public void onElectedToBeLeader() {
        serviceRegistry.unregisterFromCluster();
        serviceRegistry.registerForUpdates();
        Runnable task = ()-> {
            try {
                grpcServer.startGrpcServer();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        };
        Thread thread = new Thread(task);
        thread.start();
    }

    @Override
    public void onWorker() {
        try {
            String username = System.getProperty("user.name");
            String currentServerAddress =
                    "127.0.0.1"+","+username+"," +port;
            serviceRegistry.registerToCluster(currentServerAddress);
            Runnable task = ()->Worker.startWorker(port);
            Thread thread =new Thread(task);
            thread.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }catch (KeeperException e) {
            e.printStackTrace();
        }

    }
}
