/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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 org.jboss.installer.actions.impl;

import org.jboss.galleon.ProvisioningException;
import org.jboss.installer.actions.ActionException;
import org.jboss.installer.core.LanguageUtils;
import org.wildfly.channel.UnresolvedMavenArtifactException;
import org.wildfly.prospero.api.exceptions.OperationException;

import java.nio.file.FileSystemException;
import java.util.stream.Collectors;

public class ProvisioningExceptionHandler {

    private static final String INSTALL_EAP_MISSING_ARTIFACTS = "install.eap.missing.artifacts";
    private static final String INSTALL_EAP_PROVISION_FAILED = "install.eap.provision.failed";

    private final LanguageUtils langUtils;

    public ProvisioningExceptionHandler(LanguageUtils langUtils) {
        this.langUtils = langUtils;
    }
    public ActionException handle(ProvisioningException e) {
        Throwable ex = e;
        while (ex.getCause() != null) {
            if (ex.getCause() instanceof FileSystemException) {
                FileSystemException fse = (FileSystemException) ex.getCause();
                if (fse.getMessage().endsWith("File name too long")) {
                    return new ActionException(langUtils.getString("install.eap.provision.error.path_too_long"), ex);
                } else {
                    return new ActionException(langUtils.getString("install.eap.provision.failed") + ": " + fse.getMessage(), ex);
                }
            }
            ex = ex.getCause();
        }
        return new ActionException(langUtils.getString("install.eap.provision.failed"), e);
    }

    public ActionException handle(OperationException e) {
        if (e.getCause() instanceof UnresolvedMavenArtifactException) {
            UnresolvedMavenArtifactException ex = (UnresolvedMavenArtifactException) e.getCause();
            final String missingArtifacts = ex.getUnresolvedArtifacts().stream()
                    .map(a -> a.getGroupId() + ":" + a.getArtifactId() + (a.getVersion()!=null?(":" + a.getVersion()):""))
                    .collect(Collectors.joining(","));
            return new ActionException(langUtils.getString(INSTALL_EAP_MISSING_ARTIFACTS, missingArtifacts));
        }
        return new ActionException(langUtils.getString(INSTALL_EAP_PROVISION_FAILED), e);
    }
}
