/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.smartdata.server.cluster;

import com.hazelcast.core.MemberAttributeEvent;
import com.hazelcast.core.MembershipEvent;
import com.hazelcast.core.MembershipListener;
import org.smartdata.conf.SmartConf;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.server.utils.HazelcastUtil;

public class ClusterMembershipListener implements MembershipListener {
  private final ServerDaemon daemon;
  private SmartConf conf;

  public ClusterMembershipListener(ServerDaemon daemon, SmartConf conf) {
    this.daemon = daemon;
    this.conf = conf;
  }

  @Override
  public void memberAdded(MembershipEvent membershipEvent) {
  }

  /**
   * Every time get the member remove event, need reset smart server rpc address
   * with master host's name (even though master host doesn't change in some cases).
   *
   * @param membershipEvent
   */
  @Override
  public void memberRemoved(MembershipEvent membershipEvent) {
    String rpcHost = HazelcastUtil
            .getMasterMember(HazelcastInstanceProvider.getInstance())
            .getAddress()
            .getHost();
    String rpcPort = conf
            .get(SmartConfKeys.SMART_SERVER_RPC_ADDRESS_KEY,
                    SmartConfKeys.SMART_SERVER_RPC_ADDRESS_DEFAULT)
            .split(":")[1];
    conf.set(SmartConfKeys.SMART_SERVER_RPC_ADDRESS_KEY, rpcHost + ":" + rpcPort);

    if (HazelcastUtil.isMaster(HazelcastInstanceProvider.getInstance())) {
      this.daemon.becomeActive();
    }
  }

  @Override
  public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
  }
}
