package Zookeeper;

import org.apache.zookeeper.KeeperException;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class OnElectionAction implements OnElectionCallback {


    private final ServiceRegistry serviceRegistry;
    private final Autohealer autohealer;


    public OnElectionAction(ServiceRegistry serviceRegistry, Autohealer autohealer) {
        this.serviceRegistry = serviceRegistry;
        this.autohealer = autohealer;
    }

    @Override
    public void onElectedToBeLeader() {
        serviceRegistry.unregisterFromCluster();
        serviceRegistry.registerForUpdates(autohealer);

    }

    @Override
    public void onWorker() {
        try {
            String username = System.getProperty("user.name");
            String ipAddress = InetAddress.getLocalHost().getHostAddress();
            String currentServerAddress = String.format("%s@%s", username, ipAddress);

            serviceRegistry.registerToCluster(currentServerAddress);
            serviceRegistry.registerToCluster(currentServerAddress);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }

    }
}
