/*-
 * -\-\-
 * Helios Services
 * --
 * Copyright (C) 2016 Spotify AB
 * --
 * Licensed 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 com.spotify.helios.master;

import static com.google.common.base.Optional.fromNullable;

import com.spotify.helios.servicescommon.ZooKeeperRegistrar;
import com.spotify.helios.servicescommon.coordination.Paths;
import com.spotify.helios.servicescommon.coordination.ZooKeeperClient;
import java.io.IOException;
import org.apache.curator.framework.recipes.nodes.PersistentEphemeralNode;
import org.apache.curator.framework.recipes.nodes.PersistentEphemeralNode.Mode;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Responsible for registering the Helios master with ZooKeeper.  Will continue to attempt to
 * register in the background in the event that ZK is down when the master starts.
 */
public class MasterZooKeeperRegistrar implements ZooKeeperRegistrar {

  private static final Logger log = LoggerFactory.getLogger(MasterZooKeeperRegistrar.class);

  private final String name;
  private PersistentEphemeralNode upNode;

  public MasterZooKeeperRegistrar(String name) {
    this.name = name;
  }

  @Override
  public void startUp() throws Exception {

  }

  @Override
  public void shutDown() throws Exception {
    if (upNode != null) {
      try {
        upNode.close();
      } catch (IOException e) {
        final Throwable cause = fromNullable(e.getCause()).or(e);
        log.warn("Exception on closing up node: {}", cause);
      }
    }
  }

  @Override
  public boolean tryToRegister(final ZooKeeperClient client) throws KeeperException {

    client.ensurePath(Paths.configHosts());
    client.ensurePath(Paths.configJobs());
    client.ensurePath(Paths.configJobRefs());
    client.ensurePath(Paths.statusHosts());
    client.ensurePath(Paths.statusMasters());
    client.ensurePath(Paths.historyJobs());
    client.ensurePath(Paths.configDeploymentGroups());
    client.ensurePath(Paths.statusDeploymentGroups());

    if (upNode == null) {
      final String upPath = Paths.statusMasterUp(name);
      client.ensurePath(upPath, true);
      upNode = client.persistentEphemeralNode(upPath, Mode.EPHEMERAL, new byte[]{});
      upNode.start();
    }

    log.info("ZooKeeper registration complete");
    return true;
  }
}
