/*-
 * ~~~~~~licensing~~~~~~
 * nexus-deployer
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * 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.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.system.deployer.nexus.deployer;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import org.apache.cxf.helpers.IOUtils;
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import ru.entaxy.esb.system.deployer.api.BundleRepository;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class NexusRepositoryImpl implements BundleRepository {

    private static final String NEXUS_ADDRESS = "/service/rest/v1";
    private static final String BLUEPRINT_CLASSIFIER = "blueprint";

    private String nexusHost;
    private String nexusRepository;
    private String userName;
    private String password;

    @Override
    public String deployBlueprint(String groupId, String version, String name, String extension, byte[] data) throws IOException, AuthenticationException {
        HttpPost httpPost = new HttpPost(nexusHost + NEXUS_ADDRESS + "/components?repository=" + nexusRepository);
        Artifact artifactInfo = new DefaultArtifact(groupId, name, BLUEPRINT_CLASSIFIER, extension, version);

        addAuth(httpPost);
        httpPost.setEntity(createMultipartEntityBuilder(artifactInfo, data).build());

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
            checkAnswer(response);
        }
        return String.format("blueprint:mvn:%s/%s/%s/%s", artifactInfo.getGroupId(), artifactInfo.getArtifactId(), artifactInfo.getVersion(), artifactInfo.getExtension());
    }

    @Override
    public void delete(String groupId, String version, String name, String extension)
            throws IOException, AuthenticationException {

        Artifact artifactInfo = new DefaultArtifact(groupId, name,
                BLUEPRINT_CLASSIFIER, extension, version);

        HttpGet httpGet = new HttpGet(nexusHost + NEXUS_ADDRESS + "/search?repository=" + nexusRepository +
                "&group=" + artifactInfo.getGroupId() + "&name=" + artifactInfo.getArtifactId());

        addAuth(httpGet);

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpGet)) {
            deleteAllVersionArtifact(getListArtifactInfo(response));
            checkAnswer(response);
        }
    }

    private void deleteAllVersionArtifact(List<LinkedTreeMap> artifactList) throws AuthenticationException, IOException {
        for (LinkedTreeMap artifactInfo : artifactList) {
            if (artifactInfo.containsKey("id")) {
                deleteArtifact(String.valueOf(artifactInfo.get("id")));
            }
        }
    }

    private void deleteArtifact(String id) throws AuthenticationException, IOException {
        HttpDelete httpDelete = new HttpDelete(nexusHost + NEXUS_ADDRESS + "/components/" + id);
        addAuth(httpDelete);

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpDelete)) {
            checkAnswer(response);
        }

    }

    private void checkAnswer(CloseableHttpResponse response) throws HttpResponseException {
        if (response.getStatusLine().getStatusCode() != 204 && response.getStatusLine().getStatusCode() != 200) {
            throw new HttpResponseException(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
        }
    }

    private void addAuth(HttpRequest httpRequest) throws AuthenticationException {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(userName, password);
        httpRequest.addHeader(new BasicScheme().authenticate(creds, httpRequest, null));
    }

    private List getListArtifactInfo(CloseableHttpResponse response) throws IOException {
        if (response.getEntity() != null && response.getEntity().getContent() != null) {
            Map content = new Gson().fromJson(IOUtils.toString(response.getEntity().getContent()), Map.class);
            return (List) content.get("items");
        }
        return null;
    }

    private MultipartEntityBuilder createMultipartEntityBuilder(Artifact artifactInfo, byte[] body) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("maven2.asset1", body);
        builder.addTextBody("maven2.groupId", artifactInfo.getGroupId());
        builder.addTextBody("maven2.artifactId", artifactInfo.getArtifactId());
        builder.addTextBody("maven2.version", artifactInfo.getVersion());
        builder.addTextBody("maven2.asset1.extension", artifactInfo.getExtension());
//        builder.addTextBody("maven2.asset1.classifier", artifactInfo.getClassifier());

        return builder;
    }

    public void setNexusHost(String nexusHost) {
        this.nexusHost = nexusHost;
    }

    public void setNexusRepository(String nexusRepository) {
        this.nexusRepository = nexusRepository;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
