package Zookeeper;

import org.apache.zookeeper.KeeperException;

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() throws InterruptedException, KeeperException {
        serviceRegistry.unregisterFromCluster();
        serviceRegistry.registerForUpdates();
    }

    @Override
    public void onWorker() {
        try {
            String username = System.getProperty("user.name");
            String currentServerAddress =
                    "192.168.56.116"+","+username+"," +port;
            serviceRegistry.registerToCluster(currentServerAddress);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }catch (KeeperException e) {
            e.printStackTrace();
        }

    }
}
