/*
 * 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.apache.geode.management.internal.cli.commands.lifecycle;

import static org.apache.geode.management.internal.cli.shell.MXBeanProvider.getMemberMXBean;

import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.AbstractLauncher;
import org.apache.geode.distributed.ServerLauncher;
import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.internal.util.StopWatch;
import org.apache.geode.management.MemberMXBean;
import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.cli.ConverterHint;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.internal.cli.commands.GfshCommand;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;

import java.util.concurrent.TimeUnit;

public class StopServerCommand implements GfshCommand {
  private static final long WAITING_FOR_STOP_TO_MAKE_PID_GO_AWAY_TIMEOUT_MILLIS = 30 * 1000;

  @CliCommand(value = CliStrings.STOP_SERVER, help = CliStrings.STOP_SERVER__HELP)
  @CliMetaData(shellOnly = true,
      relatedTopic = {CliStrings.TOPIC_GEODE_SERVER, CliStrings.TOPIC_GEODE_LIFECYCLE})
  public Result stopServer(
      @CliOption(key = CliStrings.STOP_SERVER__MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
          help = CliStrings.STOP_SERVER__MEMBER__HELP) final String member,
      @CliOption(key = CliStrings.STOP_SERVER__PID,
          help = CliStrings.STOP_SERVER__PID__HELP) final Integer pid,
      @CliOption(key = CliStrings.STOP_SERVER__DIR,
          help = CliStrings.STOP_SERVER__DIR__HELP) final String workingDirectory) {
    ServerLauncher.ServerState serverState;

    try {
      if (StringUtils.isNotBlank(member)) {
        if (!isConnectedAndReady()) {
          return ResultBuilder.createUserErrorResult(CliStrings
              .format(CliStrings.STOP_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Cache Server"));
        }

        final MemberMXBean serverProxy = getMemberMXBean(member);

        if (serverProxy != null) {
          if (!serverProxy.isServer()) {
            throw new IllegalStateException(CliStrings
                .format(CliStrings.STOP_SERVER__MEMBER_IS_NOT_SERVER_ERROR_MESSAGE, member));
          }

          serverState = ServerLauncher.ServerState.fromJson(serverProxy.status());
          serverProxy.shutDownMember();
        } else {
          return ResultBuilder.createUserErrorResult(CliStrings
              .format(CliStrings.STOP_SERVER__NO_SERVER_FOUND_FOR_MEMBER_ERROR_MESSAGE, member));
        }

      } else {
        final ServerLauncher serverLauncher =
            new ServerLauncher.Builder().setCommand(ServerLauncher.Command.STOP)
                .setDebug(isDebugging()).setPid(pid).setWorkingDirectory(workingDirectory).build();

        serverState = serverLauncher.status();
        serverLauncher.stop();
      }

      if (AbstractLauncher.Status.ONLINE.equals(serverState.getStatus())) {
        getGfsh().logInfo(
            String.format(CliStrings.STOP_SERVER__STOPPING_SERVER_MESSAGE,
                serverState.getWorkingDirectory(), serverState.getServiceLocation(),
                serverState.getMemberName(), serverState.getPid(), serverState.getLogFile()),
            null);

        StopWatch stopWatch = new StopWatch(true);
        while (serverState.isVmWithProcessIdRunning()) {
          Gfsh.print(".");
          if (stopWatch.elapsedTimeMillis() > WAITING_FOR_STOP_TO_MAKE_PID_GO_AWAY_TIMEOUT_MILLIS) {
            break;
          }
          synchronized (this) {
            TimeUnit.MILLISECONDS.timedWait(this, 500);
          }
        }

        return ResultBuilder.createInfoResult(StringUtils.EMPTY);
      } else {
        return ResultBuilder.createUserErrorResult(serverState.toString());
      }
    } catch (IllegalArgumentException | IllegalStateException e) {
      return ResultBuilder.createUserErrorResult(e.getMessage());
    } catch (VirtualMachineError e) {
      SystemFailure.initiateFailure(e);
      throw e;
    } catch (Throwable t) {
      SystemFailure.checkFailure();
      return ResultBuilder.createShellClientErrorResult(String.format(
          CliStrings.STOP_SERVER__GENERAL_ERROR_MESSAGE, toString(t, getGfsh().getDebug())));
    } finally {
      Gfsh.redirectInternalJavaLoggers();
    }
  }

  private void stop(String member) {}

  private void stop(String pid, String workingDir) {}
}
