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

import com.atlassian.bitbucket.Product;
import com.atlassian.stash.internal.home.HomeDirectoryMigrationException;
import com.atlassian.stash.internal.johnson.AbstractHelpPathProvider;
import com.atlassian.stash.internal.johnson.handler.EventDetails;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanCreationException;

import javax.annotation.Nonnull;
import java.util.List;

public class HomeDirectoryMigrationHandler extends AbstractHelpPathProvider implements BeanFailureHandler {

    private static final String UPGRADE_GUIDE_URL = "https://confluence.atlassian.com/x/JAHRJQ";

    @Override
    public EventDetails handle(@Nonnull BeanCreationException exception) {
        HelpDetails help = getHelp("bitbucket.kb.upgrading.home.directory.manually", "our documentation", UPGRADE_GUIDE_URL);

        StringBuilder message = new StringBuilder("<p>The ")
                .append(Product.NAME)
                .append(" home directory could not be upgraded automatically.<ul><li>");
        Throwable cause = exception.getCause();
        if (cause instanceof HomeDirectoryMigrationException) {
            List<String> validationErrors = ((HomeDirectoryMigrationException) cause).getValidationErrors();
            message.append(StringUtils.join(validationErrors, "</li><li>"));
            Throwable rootCause = Throwables.getRootCause(cause);
            if (rootCause != null && !rootCause.equals(cause)) {
                message.append(' ').append(rootCause.getLocalizedMessage());
            }
        } else {
            message.append(cause.getLocalizedMessage());
        }
        message.append("</li></ul></p>")
                .append("<p>Please refer to <a href=\"")
                .append(help.getUrl())
                .append("\">")
                .append(help.getTitle())
                .append("</a> for more information.</p>");

        return new EventDetails("home-migration", message.toString().replace("\n", "<br/>"), cause);
    }
}
