import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;


public class LeaderElection implements Watcher {
    private static final String address = "192.168.184.10:2181";
    private static final int SESSION_TIMEOUT = 3000;
    private ZooKeeper zooKeeper;

    public static void main(String[] args) throws IOException, InterruptedException {
        LeaderElection leaderElection = new LeaderElection();
        leaderElection.connectToZookeeper();
        leaderElection.run();
    }

    public void connectToZookeeper() throws IOException {
        this.zooKeeper = new ZooKeeper(address, SESSION_TIMEOUT, this);
    }

    public void run() throws InterruptedException {
        synchronized (zooKeeper)
        {
                zooKeeper.wait();
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        switch (watchedEvent.getType()) {
            case None:
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected)
                {
                    System.out.println("Successfully connected to ZooKeeper");
                }
                else if (watchedEvent.getState() == Event.KeeperState.Closed)
                {
                    System.out.println("Connection Closed");
                    System.exit(0);
                }
                else if (watchedEvent.getState() == Event.KeeperState.Disconnected)
                {
                    System.out.println("Disconnected");
                    System.exit(0);
                }
                break;
        }
    }
}