package com.atlassian.stash.internal.johnson.handler.bean;

import com.atlassian.bitbucket.Product;
import com.atlassian.stash.internal.home.InvalidHomeDirectoryException;
import com.atlassian.stash.internal.johnson.handler.EventDetails;
import com.google.common.base.Throwables;
import org.springframework.beans.factory.BeanCreationException;

import javax.annotation.Nonnull;

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;

/**
 * @since 3.5
 */
public class HomeDirectoryDetailsFailureHandler implements BeanFailureHandler {

    // This is a STASHKB article, so it can't be defined as a help path.
    private static final String KNOWLEDGE_BASE_URL = "https://confluence.atlassian.com/x/-wG_K";

    @Override
    public EventDetails handle(@Nonnull BeanCreationException exception) {
        Throwable cause = Throwables.getRootCause(exception);
        StringBuilder message = new StringBuilder("<p>The ").append(Product.NAME).append(" home directory was not valid.")
                .append("<ul><li>").append(escapeHtml4(cause.getMessage())).append("</li></ul>");
        if (cause instanceof InvalidHomeDirectoryException) {
            message.append("</li></ul></p>")
                    .append("<p>Please refer to <a href=\"")
                    .append(escapeHtml4(KNOWLEDGE_BASE_URL))
                    .append("\">our documentation</a> for more information.</p>");
        }
        return new EventDetails("home", message.toString().replace("\n", "<br/>"), cause);
    }
}
