package com.atlassian.bitbucket.scm;

import com.atlassian.bitbucket.i18n.I18nService;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 *
 */
public class DefaultCommandExitHandler implements CommandExitHandler {
    protected final I18nService i18nService;

    public DefaultCommandExitHandler(@Nonnull I18nService i18nService) {
        this.i18nService = checkNotNull(i18nService, "i18nService");
    }

    @Override
    public void onCancel(@Nonnull String command, int exitCode, @Nullable String stdErr, @Nullable Throwable thrown) {
        if (thrown != null) {
            throw new CommandCanceledException(i18nService.createKeyedMessage("bitbucket.scm.command.canceled", command), thrown);
        }
    }

    @Override
    public void onExit(@Nonnull String command, int exitCode, @Nullable String stdErr, @Nullable Throwable thrown) {
        if (isError(command, exitCode, stdErr, thrown)) {
            onError(command, exitCode, stdErr, thrown);
        }
    }

    protected boolean isError(String command, int exitCode, String stdErr, Throwable thrown) {
        return exitCode != 0 || thrown != null || StringUtils.isNotBlank(stdErr);
    }

    protected void onError(String command, int exitCode, String stdErr, Throwable thrown) {
        if (StringUtils.isBlank(stdErr)) {
            throw new CommandFailedException(
                    i18nService.createKeyedMessage("bitbucket.scm.command.failed", command, exitCode),
                    thrown);
        }
        throw new CommandFailedException(
                i18nService.createKeyedMessage("bitbucket.scm.command.failed.saying", command, exitCode, stdErr),
                thrown);
    }
}
